在循环中读写一次后,我无法使用管道的读写功能

I cannot use pipe's write and read function after read and write once in loop

我正在学习管道,我正在尝试处理与普通管道的通信。以下代码只写入一次,但不会再次写入或读取。这是什么问题?

编辑:是的,我删除了 close() 部分,但它无法完全读取,因为写入尚未完成。

例如: 写:你好

阅读:他

阅读:llo

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

#define BUFFER_SIZE 25
#define READ_END    0
#define WRITE_END   1

int main(void)
{
char write_msg[BUFFER_SIZE] = "Game Started";
char read_msg[BUFFER_SIZE];

pid_t pid; 
int fd[2];    // an array of 2 integers fd[0] and fd[1]

if (pipe(fd) == -1) { fprintf(stderr,"Pipe failed"); return 1;}

pid = fork();

if (pid < 0) { fprintf(stderr, "Fork failed"); return 1; }
while(1){
    if (pid > 0) { 
        sprintf(write_msg,"Hello %d",rand());
        write(fd[WRITE_END], write_msg, strlen(write_msg)+1); 

    }
    else { /* child process */
        int status = read(fd[READ_END], read_msg, BUFFER_SIZE);
        if(status != -1)
        printf("child read1: %s\n                     *********************************\n",read_msg);
    }

}


return 0;

}

考虑管道的一种方法是考虑您家中的实际 管道。水(或其他流体)从一端流向另一端。如果你不断地用一桶水往管道的一端灌水,那么在另一端就无法区分当前流出的水是哪个桶输送的。

这与计算机管道基本相同:字节从一端流向另一端,没有任何特定类型的消息边界。如果需要边界,则需要自己添加。在某种程度上,您已经做到了,因为您在发送的数据中包含了字符串空终止符。

由于您有一个“消息结束字节”(字符串空终止符),确保收到完整消息的一种简单方法是在循环中逐字节读取,直到到达空终止符终结者。一旦你有了终止符,你就可以显示消息,然后返回阅读下一条消息。

代码中,它可能看起来像这样:

char ch;
while (read(pipe_read_fd, &ch, 1) == 1)
{
    if (ch == '[=10=]')
    {
        // End of message, print the buffer
    }
    else
    {
        // Append character to buffer
    }
}