【问题标题】:I cannot use pipe's write and read function after read and write once in loop在循环读取和写入一次后,我无法使用管道的写入和读取功能
【发布时间】:2020-11-20 16:15:21
【问题描述】:

我正在学习管道,我正在尝试使用普通管道进行通信。以下代码写入一次,但不会再次写入或读取。这有什么问题?

编辑:是的,我删除了 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;

}

【问题讨论】:

  • close(fd[WRITE_END]);之后,您希望如何写更多?与那里的管道的读数和关闭相同。
  • 另外,还要对write 进行错误检查。
  • 那么,如何在阅读时阻止写入?有cmets吗?
  • 你真的不需要。如果管道填满,write 将阻塞,直到它可以通过管道发送数据。与read 相同,如果没有可读取的内容,它将阻塞,直到有。
  • 但是,管道没有填满。孩子总是读,而父母写。所以父母可以写一些字符,直到孩子阅读

标签: c process pipe fork


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 2019-11-29
    相关资源
    最近更新 更多