我想测试 pclose(3) 是否会等待 shell 命令终止。我写了两个小 shell 程序。
//a.sh
#!/bin/bash
sleep 3
//b.sh
#!/bin/bash
echo "something"
sleep 3
c程序:
//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;
}
然后,编译: $ gcc -o ptest ptest.c
接下来运行ptest(我的电脑是Ubuntu 12.04.3 LTS):
$ ./ptest "sh a.sh" r
$ exit status:0
此测试将等待 shell 终止并输出退出状态 0。但是,当我按以下形式运行 ptest 时:
$ ./ptest "sh b.sh" r
$ exit status:141
这一次,ptest 没有等待 shell 程序并立即自行终止,我只是在 sleep 之前添加了一条 echo 语句,但结果不同。我不知道为什么。
最佳答案
exit status:141
是一个 SIGPIPE
错误。这个问题很好解释Why exit code 141 with grep -q?
问题是您的 b.sh
脚本尝试写入管道,但没有人在您的 C 程序中读取此管道。
关于c - 为什么 pclose(3) 不等待 shell 命令终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20611029/