从C执行另一个程序

时间:2014-07-05 16:33:29

标签: c linux exec

我想从我的C程序启动另一个程序并返回shell和PID。 这是我尝试过的。

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);

我到底错过了什么?为什么这个计划没有推出?

1 个答案:

答案 0 :(得分:2)

您无法找到错误,因为您没有检查程序中的错误。您需要检查各处的错误:

#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);
}

执行此程序会给出:

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

将exec行更改为:execlp(“invalid”,“invalid”,“invalid”,NULL),它将给出:

./run 
Unable to execute child: No such file or directory
Waiting for child...Done. Child returned: 256