有可能无法打印吗? (C,过程)

问题描述 投票:0回答:1

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>

int main() {

    pid_t c[2];
    int p[2];

    pipe(p);
    c[0] = fork();

    if (c[0] < 0) {
        fprintf(stderr, "fork error");
        exit(EXIT_FAILURE);
    } else if (c[0] == 0) {
        // First child

        close(p[1]); // unuse
        close(STDIN_FILENO);
        dup(p[0]);

        char buf[BUFSIZ];
        read(STDIN_FILENO, buf, BUFSIZ);
        printf("Second child's print: %s\n", buf); // First Child's print
    } else {
        c[1] = fork();

        if (c[1] < 0) {
            fprintf(stderr, "fork error");
            exit(EXIT_FAILURE);
        }
        else if (c[1] == 0) {
            // Second child

            close(p[0]); // unuse
            close(STDOUT_FILENO);
            dup(p[1]);
            printf("HI"); // Second child's print
        }
        else if (waitpid(c[0], NULL, 0) == -1 || waitpid(c[1], NULL, 0) == -1) {
            exit(EXIT_FAILURE);
        }
    }

    return 0;
}

我写了一段代码,第一个孩子通过第一个孩子的read()函数获取第二个孩子的write()函数的消息。

如果在打印“HI”之前第一个孩子就被收割了,我是否有可能无法打印?

如果有可能,如何解决?

c process
1个回答
0
投票

不。当第一个子进程调用

read()
时,它将阻塞等待将数据写入管道。直到第二个子进程写入管道时它才会退出,因此写入不会失败。

如果您将管道置于非阻塞模式,您设想的场景可能会发生。那么 read() 就不会等待写入内容,并且第一个子级可以在第二个子级尝试写入之前退出。如果发生这种情况,第二个孩子在调用

SIGPIPE
时会收到
write()
信号。
    

© www.soinside.com 2019 - 2024. All rights reserved.