所以我有一个名为“hello.c”的 c 程序,它除了最后的“exit(2)”之外什么都不做。我尝试在我的子进程中运行它,然后将返回值传递给我的父进程并打印相应的消息。但不知何故,程序总是在 0 处退出并打印“在 0 处退出”消息。谁能告诉我为什么?
pid_t pid;
int status;
pid = fork();
if (pid == -1){
perror("fork");
exit(1);
}
if (pid >0){
/*abusive parents*/
waitpid(pid, &status, 0);
if(WEXITSTATUS(status)==3){
printf("exit at 3\n");
}
if(WEXITSTATUS(status)==2){
printf("exit at 2\n");
}
if(!(WEXITSTATUS(status))){
printf("exit at 0\n");
}
}
else{
/*stupid child*/
execlp("hello.c",NULL);
}
return 0;}
这是 hello.c:
int main(void){
int teemo=0;
exit(2);
}
最佳答案
你不能运行一个C源文件,你需要编译(和链接)它生成一个可执行文件,然后运行这个文件。因此,你应该做类似的事情
首先编译
hello.c
(我想你正在使用gcc
)gcc -o hello hello.c
在你的第一个程序中运行
hello
execlp("./hello", "hello", NULL);
然后你应该得到你所期望的。
关于c - 使用 execlp() 运行 C 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22139996/