【发布时间】:2014-03-03 06:21:54
【问题描述】:
所以我有一个名为“hello.c”的 c 程序,它最后只做“exit(2)”。我尝试在我的子进程中运行它,然后将返回值传递给我的父进程并打印相应的消息。但不知何故,程序总是在 0 处退出并打印“exit at 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 程序,你运行编译后的可执行文件...所以
execlp("hello.c",NULL)应该是execlp("hello.bin",NULL) -
@BasileStarynkevitch 仍然得到 0。我必须先编译那个c程序吗?
-
如果你使用的是IDE,我建议你暂时停止使用它并切换到命令行工具。这应该可以帮助您获得一些相关的直觉。