【问题标题】:C - Retrieving a child's exit status that is larger than 8 bitsC - 检索大于 8 位的孩子的退出状态
【发布时间】:2016-01-22 03:57:03
【问题描述】:

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

我想要什么:

我想要一个fork()s 子进程并让它使用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("%d\n", WEXITSTATUS(status));
    }
}

我的问题:

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

我还尝试了什么:

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

那么我该如何检索大于 8 位的孩子的退出状态?

【问题讨论】:

    标签: c exec fork


    【解决方案1】:

    我不认为你试图完成它是可能的,因为在 Linux 中(实际上我认为它是 UX 特定的),进程退出代码是一个 8 位数字(最大 256):0-255(并且作为约定,0 表示成功,任何其他都表示错误)并且很多东西都依赖于这个事实(包括您使用的宏)。取以下代码:

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

    如果您编译它 (gcc a.c),然后运行生成的可执行文件 (a.out) 检查 (echo $?) 其退出代码(将被操作系统截断;嗯或是外壳吗?)它将输出 1(环绕算术):257 % 256 = 1。

    作为您提到的替代方案,您可以使用pipethis post 非常具有描述性)或套接字(AF_UNIX 类型)。

    【讨论】:

      【解决方案2】:

      此代码来自:How to send a simple string between two programs using pipes?

      作家.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: %s\n", buf);
          close(fd);
      
          return 0;
      }
      

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

      【讨论】:

        猜你喜欢
        • 2015-02-15
        • 1970-01-01
        • 1970-01-01
        • 2017-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多