简体   繁体   中英

Execute another program from C

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM