popen和pclose的差异行为

时间:2022-11-25 05:49:57

Recently, I get a strange problem when i used popen(3) and pclose(3). Just like this:

最近,当我使用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

my C program:

我的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;
}  

next, i will compile and run this program as 4 steps:

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

case 1: comment line 2, then compile and run, the program do not print 0 until the shell cmd terminate.

情况1:注释第2行,然后编译并运行,程序不打印0,直到shell cmd终止。

case 2: comment line 1, then compile and run, the program will terminate right now and it print 13, that is to say the exit status of pclose is 13, i look up the linux errno:

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

13 EACCES +Permission denied

samebody would help me and tell me the reason? thanks.

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

1 个解决方案

#1


1  

You should use the WEXITSTATUS macro to get the real return code.

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

#1


1  

You should use the WEXITSTATUS macro to get the real return code.

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