c - 为什么 pclose(3) 不等待 shell 命令终止

标签 c linux popen pclose

我想测试 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/

相关文章:

c - 如何确保输入是 C 编程语言中的 double

linux - 如何配置拇指安全性?

linux - -bash : certutil: command not found

c - 如何在 macOS 上检查密码?

python - subprocess.Popen : Different buffering for stdin, 标准输出,标准错误?

C printf 打印随机数

javascript - 将 SQL 行拆分为两行并正确构建

c - 如何在循环内获取字符而不在循环中停止?

c++ - 如何捕获在 C++ 中运行的命令的 exit_code 和 stderr?

Python,Popen 和 select - 等待进程终止或超时