the difference behaviour in popen and pclose

2019-09-16 04:00发布

问题:

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

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

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

my C program:

#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:

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

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:

13 EACCES +Permission denied

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

回答1:

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



标签: c linux