0

I want to launch another program from my C program and return the shell and PID. Here is what I've tried.

struct app_names{

const char *run_args[TOTAL_NUM_APP] = {
    " inp.in",
    " 3000 reference.dat 0 0 100_100_130_ldc.of",
}


const char *run_exe[TOTAL_NUM_APP] = {
   "./mcf",
   "./lbm"
}
};
struct app_names SPEC_RUN;



pid_t child;
child = fork();
char RUN_EXE[2048] = "";        
strcat(RUN_EXE, SPEC_RUN.run_exe[0]);
strcat(RUN_EXE, EXE_SUFIX);
strcat(RUN_EXE, SPEC_RUN.run_args[0]);

if(!child)
    execlp(SPEC_RUN.run_exe[0], SPEC_RUN.run_exe[0], SPEC_RUN.run_args[0], (char *)0);

What exactly am I missing here? why doens't the program launch?

7
  • That's probably the weirdest structure I've seen in a while. Beyond that (and the terrible buffer overflow risk with the strcats into a fixed-size buffer), have you checked the return value of execlp (and associated error, if relevant)? Commented Jul 5, 2014 at 16:39
  • 1
    Check out strerror(errno) value. Also, is your struct C valid code? Commented Jul 5, 2014 at 16:40
  • 1
    You can solve this in 30 seconds by firing up GDB and breaking to see what is the execlp parms you pass and what the value of errno is when it fails. It would have taken less time than it took to type this question. Commented Jul 5, 2014 at 16:56
  • How would you rewrite it? Or could anyone help me rewrite that struct?. Thanks. Commented Jul 5, 2014 at 19:03
  • @Jack: Yes, it is valid C code. Commented Jul 5, 2014 at 19:03

1 Answer 1

2

You can't find out wha't wrong because you don't check for errors in your program. You need to check for errors everywhere:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main (void)
{
  pid_t child;
  int status;

  child = fork();

  if (child == -1) {
    perror("Unable to fork");
    exit(EXIT_FAILURE);
  }

  if (child == 0) {
    if (execlp("echo", "echo", "hello", NULL) < 0) {
      perror("Unable to execute child");
      _exit(EXIT_FAILURE);
    }
  }

  printf("Waiting for child...");

  if (wait(&status) < 0) {
    perror("Unable to wait for child");
    exit(EXIT_FAILURE);
  }

  printf("Done. Child returned: %d\n", status);

  exit(EXIT_SUCCESS);
}

Executing this program gives:

./run 
hello
Waiting for child...Done. Child returned: 0

Change the exec line to: execlp("invalid", "invalid", "invalid", NULL) and it will give:

./run 
Unable to execute child: No such file or directory
Waiting for child...Done. Child returned: 256
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this. Let me try and then accept your answer.
I get the following msg: unable to execute child
if you are still getting the error you probably need to set the execute bit (chmod +x) on the file you are trying to execute.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.