Близкое к минимальному решению:
#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
Обратите внимание, что вы можете передавать только значения 0..255 через exit()
вкл. Системы POSIX, если только вы не попали в глубокие махинации с sigaction()
, SIGCHLD
, SA_SIGINFO
и т. Д. (И даже тогда вы получите только 4 байта данных). YMMV в системах Windows.