c - 管道中父进程的 wait() 有什么问题

标签 c concurrency process pipeline

有人问我:

  1. 下面的代码有什么问题?
  2. 如何在儿子的流程代码中修复它:
#define BUF_SIZE 4096
int my_pipe[2];
pipe(my_pipe);
char buf[BUF_SIZE];
int status = fork();

//Filled buf with message...
if (status == 0) {  /* son process */
    close(my_pipe[0]);
    write(my_pipe[1],buf,BUF_SIZE*sizeof(char));
    exit(0);
 }
 else {    /* father process */
    close(my_pipe[1]);
    wait(&status);  /* wait until son process finishes */
    read(my_pipe[0], buf, BUF_SIZE*sizeof(char));
    printf("Got from pipe: %s\n", father_buff);
    exit(0);
 }
}

所以我想出了下一个代码来尝试解决这个问题:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

#define BUF_SIZE 6

int main() {
    int my_pipe[2];
    pipe(my_pipe);

    char buf[BUF_SIZE];
    int status = fork();
    //Filled buf with message...
    for (int i = 0; i < BUF_SIZE; i++) buf[i] = 'a';

    if (status == 0) {    /* son process */
        close(my_pipe[0]);
        write(my_pipe[1], buf, BUF_SIZE * sizeof(char));
        _exit(0);
    } else {    /* father process */
        close(my_pipe[1]);
        wait(&status);    /* wait until son process finishes */
        printf("Son Status: %d\n", status);
        read(my_pipe[0], buf, BUF_SIZE * sizeof(char));
        printf("Got from pipe: %s\n", buf);
        _exit(0);
    }
}

我的第一个想法是 wait(&status) 有问题,如果子进程无法完成,这可能会导致程序无法终止。

在儿子的代码中,我相信如果管道中没有足够的空间,write 将阻塞进程,从而阻塞整个应用程序。

如果我的主张是正确的,我该如何证明呢?而且我不知道如何修复儿子的代码。

最佳答案

您对管道大小的假设是正确的,我可以使用 BUF_SIZE0x10000 重现该问题。

但解决方案不在客户这边,而在家长那边。您只需在 wait() 之前执行 read(),当然您应该始终使用返回代码来确定您收到了多少。父级的此修复不再导致阻塞:

    len = read(my_pipe[0], buf, BUF_SIZE * sizeof(char));
    if( len >= 0 ) {
            printf("Got %d from pipe\n", len );
    } else {
            perror( "read()" );
    }
    close(my_pipe[1]);
    wait(&status);    /* wait until son process finishes */
    printf("Son Status: %d\n", status);

在子进程中,您可以使用 fcntl(my_pipe[1], F_SETFL, O_NONBLOCK); 使用非阻塞 IO,因此 write() 会发送尽可能多的数据可能然后返回。当然,在这种情况下其余数据将会丢失。

关于c - 管道中父进程的 wait() 有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58877140/

相关文章:

java - 在 Java 中重定向子进程的 I/O(为什么 ProcessBuilder.inheritIO() 不起作用?)

multithreading - 为什么说 "Don' t 同时格式化软盘的评论在谈论线程和进程时很有趣?

c - 重启程序的问题

C 程序在第二次使用函数时崩溃

c - 将用户输入存储到 C 中的字符串数组中

C 标准库函数 'strncpy' 不起作用

java - 可能的 FindBugs 误报 UL_UNRELEASED_LOCK_EXCEPTION_PATH?

concurrency - 什么是协程?

java - Java HashMap 中的线程问题

c# - StartInfo 的替代权限