如何将 child 进程的 return 值获取到其使用 exec 创建的 parent?

How to get the return value of child process to its parent which was created using exec?

我看过类似的问题here and here。答案建议使用 WEXITSTATUS。但是根据 WAIT(2) 的手册页,它有一个限制。它说: WEXITSTATUS(w状态) returns child 的退出状态。 这包含状态 参数的最低有效 8 位,child 在对 exit(3) 或 _exit(2) 的调用中指定或作为参数 对于 main() 中的 return 语句。仅当 WIFEXITED returned 为真时才应使用此宏。

因此,如果 child return 的值大于 255,则 parent 无法获得正确的值。我的问题是 parent 进程如何接收大于 255 的 returned 值?谢谢

My question is how can a parent process receive the returned value which is larger than 255?

不能。进程 的 return 值必须 从 0 到 255。如果你想在子进程和父进程之间传递任何其他值,你需要某种形式的进程间通信,例如作为管道。

这取决于 o/s 及其对 SA_SIGINFO 的支持。如果您阅读 POSIX sigaction() carefully, and if you use SA_SIGINFO to capture extra information about the signals delivered, and you catch the SIGCHLD signal, then you may be able to get extra information, as documented in Signal Actions and <signal.h>.

的规范

特别是,<signal.h> 文档指出,当信号为 SIGCHLD 时,则:

int si_status

If si_code is equal to CLD_EXITED, then si_status holds the exit value of the process; otherwise, it is equal to the signal that caused the process to change state. The exit value in si_status shall be equal to the full exit value (that is, the value passed to _exit(), _Exit(), or exit(), or returned from main()); it shall not be limited to the least significant eight bits of the value.

Linux sigaction() 的文档表明 Linux 支持此功能。然而,它比使用 waitpid() 或其函数家族之一更难组织,而且我还没有证明它确实如 POSIX 指定的那样工作。