【发布时间】:2013-03-22 06:23:12
【问题描述】:
我有一个使用popen 和pclose 的程序:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
int main(void)
{
FILE *fp = NULL;
int ret_val = 0;
fp = popen("ls *", "r");
if (NULL == fp)
{
printf("popen error\n");
return 1;
}
ret_val = pclose(fp);
if (-1 == ret_val)
{
printf("pclose error\n");
return 1;
}
else
{
printf("%d,%d,%d\n",ret_val, WIFEXITED(ret_val), WEXITSTATUS(ret_val));
}
return 0;
}
程序的输出是:
./test
Broken Pipe
36096,1,141
我的问题是:
- 为什么会出现“断管”?
- 为什么退出状态码是 141?我认为“ls *”已执行 成功,因此退出状态应为 0。
【问题讨论】:
-
你了解 Unix 中的管道吗?比如你知道在命令行输入
cat /etc/motd | more会发生什么吗? -
@AhmedMasud: cat /etc/motd | more:cat /etc/motd 的输出将是 more 的输入。这样对吗?谢谢你的建议!
-
@AhmedMasud:我知道,因为有一个“破管道”,“ls *”没有成功执行。所以退出状态是141。但是为什么会出现“断管”呢?我无法找出根本原因。
-
@AhmedMasud:我认为“Broken pipe”是由“ls *”输出的。因为我的程序没有使用 fgets 来获取输出,直接关闭管道。 “ls *”输出“Broken pipe”。对吗?
-
@AnishRam:我同意你的解释。非常感谢!