繁体   English   中英

如何刷新协同进程管道中的I / O缓冲区

[英]How to flush I/O buffer in coprocess's pipe

我正在使用管道来编写协同进程。 父级创建两个管道,一个管道用于写入子级,另一个用于从子级读取。 但是当我运行程序时,它正在等待,因为它将printf设置为完全缓冲为默认值。 我不想在子进程源代码中刷新缓冲区。

我知道UNIX环境中高级编程的第19章介绍了一种使用伪终端的方法。 但我想知道是否有更多的样本方法。 谢谢大家。

这是我的源代码:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>


int main()
{
    #define MAXSIZE 1024

    char workload[MAXSIZE];
    char result[MAXSIZE];
    char buf[10] = {0};
    workload[strlen(workload)] = EOF;
    int workload_size = strlen(workload);

    int fd1[2], fd2[2];
    int n;
    pid_t pid;
    if (pipe(fd1) < 0 || pipe(fd2) < 0) {
        fprintf(stderr, "pipe error: %s\n", strerror(errno));
        exit(1);
    }

    if ((pid = fork()) < 0) {
        fprintf(stderr, "fork error: %s\n", strerror(errno));
        exit(1);
    } else if (pid > 0) {
        close(fd1[0]);
        close(fd2[1]);
        while(fgets(workload, MAXSIZE, stdin) != NULL)
        {
            workload_size = strlen(workload);
            if (write(fd1[1], workload, workload_size) != workload_size) {
                fprintf(stderr, "write to pipe error: %s\n", strerror(errno));
                exit(1);
            }

            if ((n = read(fd2[0], result, MAXSIZE)) < 0) {
                fprintf(stderr, "read from pipe error: %s\n", strerror(errno));
                exit(1);
            }

            if (n == 0) {
                fprintf(stderr, "child closed the pipe\n");
                exit(1);
            }

            result[n] = 0;

            if (puts(result) == EOF) {
                fprintf(stderr, "fputs error\n");
                exit(1);
            }
        }
    } else {
        close(fd1[1]);
        close(fd2[0]);
        if (fd1[0] != STDIN_FILENO) {
            if (dup2(fd1[0] ,STDIN_FILENO) != STDIN_FILENO) {
                fprintf(stderr, "dup2 error to stdin.\n");
                exit(1);
            }
            close(fd1[0]);
        }
        if (fd2[1] != STDOUT_FILENO) {
            if (dup2(fd2[1] ,STDOUT_FILENO) != STDOUT_FILENO) {
                fprintf(stderr, "dup2 error to stdout.\n");
                exit(1);
            }
            close(fd2[1]);
        }

        if (execl("./a.out", "a.out", NULL) < 0) {
            fprintf(stderr, "execl error: %s\n", strerror(errno));
            exit(1);
        }
        exit(0);
    }

    return 0;
}

子进程只是从标准输入读取并输出它:

#include <stdio.h>

int main()
{
    #define MAXSIZE 1024
    char x[MAXSIZE];
    int n;
    while(fgets(x, 1024, stdin) != NULL)
    {
        printf("%s", x);
    }
    return 0;
}

您可以使用stdbuf实用程序更改子进程的缓冲。

或者,如果您可以更改子进程的代码,请直接从子进程调用setvbuf

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM