c - 在同一管道上多次写入和读取?

标签 c pipe

我目前正在查看以下在 C 中使用管道的代码:

/*****************************************************************************
Excerpt from "Linux Programmer's Guide - Chapter 6"
(C)opyright 1994-1995, Scott Burkett
***************************************************************************** 
MODULE: pipe.c
*****************************************************************************/

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

int main(void)
{
    int     fd[2], nbytes;
    pid_t   childpid;
    char    string[] = "Hello, world!\n";
    char    readbuffer[80];

    pipe(fd);

    if((childpid = fork()) == -1)
    {
            perror("fork");
            exit(1);
    }

    if(childpid == 0)
    {
            /* Child process closes up input side of pipe */
            close(fd[0]);

            /* Send "string" through the output side of pipe */
            write(fd[1], string, (strlen(string)+1));
            exit(0);
    }
    else
    {
            /* Parent process closes up output side of pipe */
            close(fd[1]);

            /* Read in a string from the pipe */
            nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
            printf("Received string: %s", readbuffer);
    }

    return(0);
}

此代码只能将字符串传输一次给父级。我现在正在尝试向父级发送第二个字符串。做第二个写语句(是的,我创建了一个 string2):

write(fd[1], string, (strlen(string)+1));
write(fd[1], string2, (strlen(string2)+1));

为了让父级注册第二次写入,我还需要做什么?

谢谢你的帮助

最佳答案

冒着明显的风险,尝试:

        /* Send "string" through the output side of pipe */
        write(fd[1], string, (strlen(string)+1));
        write(fd[1], string, (strlen(string)+1));
        // etc.
        exit(0);
     }
      else
     {
        /* Parent process closes up output side of pipe */
        close(fd[1]);

        /* Read in a string from the pipe */
        nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
        printf("Received string: %s", readbuffer);

        nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
        printf("Received string: %s", readbuffer);

        // etc.

也就是说,只写更多的字符串并且更重要的是还要阅读它们!?但您可能在问其他问题,所以请澄清您的问题。

关于c - 在同一管道上多次写入和读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18820006/

相关文章:

c - 使用指针在 C 中解析 TFTP 数据包的字符串

c++ - 当一个相对较大的浮点值与两个相对较小的浮点值相乘时,消除误差的最佳算术顺序是什么

python - 在 python 和 c++ 之间管道传输二进制数据

linux - 如何过滤流/管道以删除空部分的 header ?

计算第二个RC4 key 字节为0x00的事件的频率

c - 函数内的数组声明

C 编译错误

C:pipe 如何在同一管道上多次写入数据?

scala - Spark 管示例

docker - 带有OpenSSL和stdin,stdout的Docker Exec