通过管道发送多条消息

时间:2015-04-16 22:51:39

标签: c linux pipe

我正在尝试发送两条消息" hello World"和#34;再见"从父母到使用烟斗的孩子。孩子在收到信息时必须打印信息。 我的问题是如何发送第二条消息。我编译并运行该程序,但它只打印第一条消息。任何sugestions? 这是我的代码:

#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);
    }
}

1 个答案:

答案 0 :(得分:2)

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

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");
}