-C BEGINNER-在没有管道的子进程和父进程之间传递数据

问题描述 投票:-1回答:1

我被告知我们可以通过在子进程中使用exit(v)并在父进程中使用wait()来传递值v,然后使用WEXITSTATUS()来检索v。我已经浏览了网络,但找不到解决方案。任何想法或代码将不胜感激。

c linux
1个回答
0
投票

几乎是最小的解决方案是:

#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。

© www.soinside.com 2019 - 2024. All rights reserved.