pclose() 返回管道的终止状态是否在所有平台上都向左移动了 8 位?

Does pclose() return pipe's termination status shifted left by eight bits on all platforms?

本文关键字:平台 左移 移动 管道 返回 终止 是否 状态 pclose      更新时间:2023-10-16

我在 Centos4 上发现 popen(( 的手册页部分声明:

DESCRIPTION
   The  pclose()  function shall close a stream that was opened by popen(), wait for the command to termi-
   nate, and return the termination status of the process that was running  the  command  language  inter-
   preter.   However, if a call caused the termination status to be unavailable to pclose(), then pclose()
   shall return -1 with errno set to [ECHILD] to report this situation.

但是,在我的C++应用程序中,当我实际执行代码时,我看到终止状态向左移动了 8 位。 也许这是为了将管道终止状态的 -1 与 pclose(( 自己的退出状态 -1 区分开来?

这是便携式行为吗? 为什么手册页没有提到这一点? 如果不是可移植的,哪些平台符合此行为?

只是为了在上面的 shooper 答案中添加一些代码,您可能想按照以下行做一些事情:

#include <sys/wait.h>
//Get your exit code...
int status=pclose(pipe);
//...and ask how the process ended to clean up the exit code.
if(WIFEXITED(status)) {
    //If you need to do something when the pipe exited, this is the time.
    status=WEXITSTATUS(status);
}
else if(WIFSIGNALED(status)) {
    //If you need to add something if the pipe process was terminated, do it here.
    status=WTERMSIG(status);
}
else if(WIFSTOPPED(status)) {
    //If you need to act upon the process stopping, do it here.
    status=WSTOPSIG(status);
}

除此之外,根据需要添加优雅。

如果你考虑一下,那里有一个"分叉",所以你可能想要"WIFEXITED"和"WEXITSTATUS"。

从手册页:

pclose(( 函数等待关联的进程终止,并返回 wait4(2( 返回的命令的退出状态。