popen和pclose的差异行为

时间:2013-12-16 09:32:06

标签: c linux

最近,当我使用popen(3)pclose(3)时,我遇到了一个奇怪的问题。就像这样:

//a.sh
#!/bin/bash
cat /etc/issue
sleep 3

//b.sh
#!/bin/bash
cat /etc/issue
echo "before sleep"
sleep 3

我的C程序:

#include <stdio.h>
int main(void) {
1:    FILE *fl = popen("sh a.sh", "r");
2:    FILE *fl = popen("sh b.sh", "r");
      int t = pclose(fl);
      printf("%d\n", t);
      return 0;
}  

接下来,我将编译并运行该程序,分为4个步骤:

案例1:注释第2行,然后编译并运行,程序在shell cmd终止之前不打印0。

案例2:注释第1行,然后编译并运行,程序将立即终止并打印13,也就是说pclose的退出状态为13,我查找linux错误:< / p>

13 EACCES +Permission denied

同一个人会帮助我并告诉我原因?感谢。

1 个答案:

答案 0 :(得分:1)

您应该使用WEXITSTATUS宏来获取真实的返回码。