如何检测 popen 中的失败命令?
How do I detect a failing command in popen?
我正在尝试弄清楚如何检测 popen 调用的命令何时失败。在下面的程序 test.c
中,尽管命令失败,但 popen returns 非空。有什么线索吗?
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
int status;
fp = popen("foo", "r");
if (fp != NULL) {
puts("command successful");
status = pclose(fp);
if (status < 0) {
perror(NULL);
exit(EXIT_FAILURE);
}
} else {
perror(NULL);
exit(EXIT_FAILURE);
}
return 0;
}
输出:
$ ./test
command successful
sh: 1: foo: not found
据我了解 man page,pclose
应该 return 退出代码。您在此处测试 <0,如果 pclose
本身失败,则为真。然后测试 >0 将测试被调用程序是否失败(退出代码 >0)。
pclose
的手册页:
The pclose() function waits for the associated process to terminate and returns the exit status of the command as returned by wait4.
和
The pclose() function returns -1 if wait4 returns an error, or some other error is detected.
我正在尝试弄清楚如何检测 popen 调用的命令何时失败。在下面的程序 test.c
中,尽管命令失败,但 popen returns 非空。有什么线索吗?
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
int status;
fp = popen("foo", "r");
if (fp != NULL) {
puts("command successful");
status = pclose(fp);
if (status < 0) {
perror(NULL);
exit(EXIT_FAILURE);
}
} else {
perror(NULL);
exit(EXIT_FAILURE);
}
return 0;
}
输出:
$ ./test
command successful
sh: 1: foo: not found
据我了解 man page,pclose
应该 return 退出代码。您在此处测试 <0,如果 pclose
本身失败,则为真。然后测试 >0 将测试被调用程序是否失败(退出代码 >0)。
pclose
的手册页:
The pclose() function waits for the associated process to terminate and returns the exit status of the command as returned by wait4.
和
The pclose() function returns -1 if wait4 returns an error, or some other error is detected.