3

我在 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 区分开来?

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

4

2 回答 2

2

只是为了在上面的购物者答案中添加一些代码,您可能想要在以下几行中做一些事情:

#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);
}

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

于 2019-09-03T05:08:31.180 回答
0

如果你仔细想想,那里有一个“叉子”,所以你可能想要“WIFEXITED”和“WEXITSTATUS”。

从手册页:

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

于 2014-12-12T22:46:34.453 回答