Frage

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 .

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top