[英]Execute another program from C
我想從我的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);
我在這里到底想念什么? 為什么程序不啟動?
您不會發現沒有錯,因為您不檢查程序中的錯誤。 您需要檢查所有地方的錯誤:
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.