【问题标题】:multiple messages through a pipe通过管道发送多条消息
【发布时间】:2015-04-17 07:13:43
【问题描述】:

我正在尝试使用管道从父母向孩子发送两条消息“hello World”和“Goodbye”。孩子收到消息后必须打印出来。 我的问题是如何发送第二条消息。我编译并运行程序,但它只打印第一条消息。有什么建议吗? 这是我的代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50

void main(){

    int fd[2], n, status;
    char buf[MAX];
    pid_t pid;
    char str1[]="Hello World!\n";
    char str2[]="Goodbye\n";
    pipe(fd);

    if((pid=fork())<0){
        abort();
    }

    else if(pid>0){// parent code goes here
        close (fd[0]); // close read channel of parent

        /*Send "hello world" through the pipe*/

        write(fd[1],str1,(strlen(str1))); // write to the pipe

        wait(&status);

        close(fd[0]);
        write(fd[1],str2,(strlen(str2)));
    }  
    else{ // child code goes here
        close(fd[1]); // close write channel of child

        n=read(fd[0], buf, sizeof(buf)); // reads from the pipe
        write(STDOUT_FILENO, buf, n);

        exit(0);
    }
}

【问题讨论】:

  • 为什么要在父级中关闭fd[0] 两次?
  • wait 等待子进程退出。为什么你在孩子完成后尝试向管道写一些东西并且不会尝试读取它?
  • 第二次关闭没有意义,你是对的。我的错误我试图等待孩子结束在管道上再次写,但我真的不知道这是否正确。 ://
  • 建议在编译时启用所有警告。然后 'void main()' 将被更正为 'int main(void)' 并包含头文件 'sys/types.h' 以便定义 'pid_t'。
  • 关于行:'wait(&status)' 等待子退出,同时捕获退出状态/值。可能不是你想做的。为什么代码关闭 fd[0] 不止一次? “管道”不知道 EOF、记录或任何格式。读取管道的代码需要考虑到这一点,

标签: c linux pipe


【解决方案1】:

在父级中,只写两条消息,然后关闭管道的写端:

close(fd[0]); // close read channel of pipe in parent
write (fd[1], str1, strlen(str1)); // write "hello world"
write (fd[1], str2, strlen(str2)); // write "goodbye"
close(fd[1]); // Tell child that we're done writing

wait(&status); // Wait for child to read everything and exit

在孩子中,您应该循环阅读,直到获得 EOF,由 read() 返回 0 表示:

close(fd[1]); // close write channel of pipe in child
while ((n = read(fd[0], buf, sizeof(buf)) > 0) { // Read until it returns 0 (EOF) or -1 (error)
    write(STDOUT_FILENO, buf, n);
}
if (n < 0) { // -1 = error
    perror("read from pipe");
}

【讨论】:

  • 是的,它有效!非常感谢!!!但我不明白while条件。 n 是整数吗? n 是什么意思?读取函数赋予 n 的值是多少?
  • 读取的字节数。你在自己的程序中使用过,怎么会不知道它是什么?
  • 我有一个想法,只是为了确保我没有错!非常感谢。 :)
猜你喜欢
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多