我创建了以下程序,该程序应该返回进程ID和子进程的退出代码。应该使用非零退出代码打印出进程。我不知道我是否正确地做到了。这是对的吗?
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
int main() {
int pid = fork();
if (pid < 0) {
printf("Could not fork\n");
exit(1);
}
else if (pid == 0) {
execvp(arg[0], arg);
exit(0);
}
else {
wait(NULL);
if (errno != 0) {
printf("%d returned code %d", getpid(), errno);
}
}
}
答案 0 :(得分:1)
来自人等待 here
WEXITSTATUS(status)
returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a
call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should be employed only if WIFEXITED returned
true.
Return Value
wait(): on success, returns the process ID of the terminated child; on error, -1 is returned.
因此大致,您的代码应如下所示
int stat;
pid_t cpid = wait( &stat );
if ( WIFEXITED(stat) ) {
printf("%d returned code %d", cpid , WEXITSTATUS(stat));
}