我被告知我们可以通过在子进程中使用exit(v)并在父进程中使用wait()来传递值v,然后使用WEXITSTATUS()来检索v。我已经浏览了网络,但找不到解决方案。任何想法或代码将不胜感激。
几乎是最小的解决方案是:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "failed to fork\n");
return -1;
}
else if (pid == 0)
{
exit(42); // The Answer to Life, the Universe, and Everything
}
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
{
if (WIFEXITED(status))
printf("PID %d exited with status %d\n", corpse, WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("PID %d died from signal %d\n", corpse, WTERMSIG(status));
else
printf("PID %d exited with status 0x%.4X (which is neither exited nor terminated)\n",
corpse, status);
}
return 0;
}
运行时产生:
PID 28883 exited with status 42
[请注意,除非您使用exit()
,sigaction()
,SIGCHLD
等深入理解,否则只能通过POSIX系统上的SA_SIGINFO
传递值0..255。数据的)。 Windows系统上的YMMV。