C - 检索大于 8 位的孩子退出状态



注意:为了简单起见,我没有包含太多的错误检查,并且我的示例代码实际上没有任何实际用途。

我想要的:

我想要一个程序,fork()是一个子进程,并让它调用使用execl()的进程。然后,父节点检索该流程的退出代码。这是相当琐碎的。

我尝试了什么:

int main(int argc, char** argv) {
    int ch = fork();
    if(ch == -1) {
        perror(NULL);
    }else if(ch == 0) {
        // In child, invoke process
        execl("/path/process", "process", 0);
    }else {
        // In parent, retrieve child exit code
        int status = 0;
        wait(&status);
        // print exit status
        if(WIFEXITED(status)) printf("%dn", WEXITSTATUS(status));
    }
}
我问题:

WEXITSTATUS()仅检索出口值的较低8位,而我需要int值的所有位。具体来说,process执行计算,结果可能大于8位。它甚至可能是负数,在这种情况下,最高位将需要表示正确的值。

此外,在环顾四周时,我发现了pipe()函数。但是,我不确定如何在这种情况下使用它,因为在调用execl()之后,我无法从子进程中写入文件描述符。

那么我如何去检索大于8位的子节点退出状态呢?

我不认为你想要完成的是可能的,因为在Linux中(实际上我认为这是特定于UX的),进程退出代码是一个8位数字:0-255(作为惯例,0意味着成功,其他任何东西都意味着错误),很多东西都依赖于这个事实(包括你使用的宏)。以下面这段代码为例:

// a.c
int main() {
    return 257;
}

如果您编译它(gcc a.c),并运行结果可执行文件(a.out)检查(echo $?)其退出代码(将被操作系统截断;),它将输出1(将算术括起来):257% 256 = 1.

作为您提到的替代方案,您可以使用pipe(这篇文章是相当描述性的)或套接字(AF_UNIX类型)。

这段代码来自:如何使用管道在两个程序之间发送一个简单的字符串?

writer.c

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
    int fd;
    char * myfifo = "/tmp/myfifo";
    /* create the FIFO (named pipe) */
    mkfifo(myfifo, 0666);
    /* write "Hi" to the FIFO */
    fd = open(myfifo, O_WRONLY);
    write(fd, "Hi", sizeof("Hi"));
    close(fd);
    /* remove the FIFO */
    unlink(myfifo);
    return 0;
}

reader.c

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
    int fd;
    char * myfifo = "/tmp/myfifo";
    char buf[MAX_BUF];
    /* open, read, and display the message from the FIFO */
    fd = open(myfifo, O_RDONLY);
    read(fd, buf, MAX_BUF);
    printf("Received: %sn", buf);
    close(fd);
    return 0;
}

代码,可能是父/阅读器,应该删除fifo节点,也许通过调用rm。否则,fifo条目将保留,即使在重新启动时也是如此,就像任何其他文件一样。

最新更新