I am trying to get the exist status of the child process using popen()
.
Case 1: Calling function with the shell command returning error. This is working as expected.
func("du -sh _invalid_file_");
Output:
du: cannot access '_invalid_file_': No such file or directory
Child exit value: 1
Here the child exist status is same as the exit value of du
which ran in bash
.
$ du -sh _invalid_file_
du: cannot access '_invalid_file_': No such file or directory
$
$ echo $?
1
$
Case 2: (Error case) Calling function with the below shell command returning success.
In my code, WEXITSTATUS()
returning non-zero
value but the same command in bash
returning 0
.
func("du -sh");
Output:
Child exit value: 141
Please suggest to fix this issue. Pasted the code below.
int func(char *cmd)
{
FILE *pfp = NULL;
int retval, status;
pfp = popen(cmd, "r");
if (pfp == NULL) {
perror("popen failed");
exit(1);
}
status = pclose(pfp);
if (status < 0) {
perror("pclose error");
} else {
if (WIFEXITED(status)) {
retval = WEXITSTATUS(status);
printf("Child exit value: %d\n", retval);
}
}
return 0;
}