c - wait() 等待子进程崩溃

标签 c fork pipe wait

我有以下程序

int external_apply(char *type)
{
    int pfds[2];
    if (pipe(pfds) < 0)
        return -1;

    if ((pid = fork()) == -1)
        goto error;

    if (pid == 0) {
        /* child */

        const char *argv[8];
        int i = 0;
        argv[i++] = "/bin/sh";
        argv[i++] = "script_file.sh";
        argv[i++] = "apply";

        close(pfds[0]);
        dup2(pfds[1], 1);
        close(pfds[1]);

        execvp(argv[0], (char **) argv);
        exit(ESRCH);

    } else if (pid < 0)
        goto error;

    /* parent */
    close(pfds[1]);

    int status;
    while (wait(&status) != pid) {
        printf("waiting for child to exit");
    }

    return 0;

error:
    close(pfds[0]);
    return -1;
}

fork 调用我的脚本文件。脚本文件包含导致管道关闭(有时)的命令。如果管道被 scipt 关闭,则等待将导致程序崩溃。

如何避免脚本关闭管道时程序崩溃?

最佳答案

出现错误时,将 return -1 替换为 _exit(-1)

关于c - wait() 等待子进程崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17070425/

相关文章:

jenkins - Jenkins 管道sh似乎不尊重shell命令中的管道

c - 在子进程和父进程中,变量具有相同的地址但具有不同的值?

c++ - 文件重定向运算符 ">"不适用于 CreateProcess() API

c - c 中的结构和文件

c - 通过引用传递 char

xcode - Xcode 如何在 Debug模式下跟踪子进程?

c - Socket编程——服务端内容写入客户端(write())

perl - 当后台进程在 Perl 中终止时,如何通知我?

python - os.fork 和 multiprocessing.Process 之间的行为差​​异

linux - 将命令 'ls | grep x' 从 linux 转换为 DOS