1

I want to test the pclose(3) whether it will wait the shell command terminate.I write two little shell program.

//a.sh
#!/bin/bash
sleep 3

//b.sh
#!/bin/bash
echo "something"
sleep 3

c program:

//ptest.c

#include <stdio.h>
#include <sys/wait.h>

int main(int argc, char **argv) {
    char *filename = argv[1];
    char *mode = argv[2];
    FILE *fl = popen(filename, &mode);
    int t = pclose(fl);
    if(WIFEXITED(t)) {
        printf("exit status:%d\n", WEXITSTATUS(t));
    }
    return 0;
}

then, compile: $ gcc -o ptest ptest.c

next run the ptest(my computer is Ubuntu 12.04.3 LTS):

$ ./ptest "sh a.sh" r
$ exit status:0

this test will wait the shell terminate and output exit status 0.However when I run the ptest as following form:

$ ./ptest "sh b.sh" r
$ exit status:141

this time, ptest don't wait shell program and terminate itself immediately, I just add an echo statement before the sleep, But the result was different. I don't know why .

yuxing
  • 47
  • 1
  • 6

1 Answers1

1

exit status:141 is a SIGPIPE error. It is well explained in this question Why exit code 141 with grep -q?

The issue is that your b.sh script tries to write to the pipe, but nobody is reading this pipe in your C program.

Community
  • 1
  • 1
Didier Trosset
  • 36,376
  • 13
  • 83
  • 122
  • But, as the apue said:"If we write to a pipe whose read end has been closed, the signal SIGPIPEis generated" on the chapter 15.2, in my case, I don't close the read end and just don't read the pipe. In addition, when I call the pclose(3), the echo command in the b.sh has finished possibility. – yuxing Dec 17 '13 at 02:41