我试着用一根管子把父母的“你好世界”和“再见”两个信息发给孩子。孩子收到信息时必须打印出来。
我的问题是如何发送第二条信息。我编译并运行程序,但它只打印第一条消息。有什么建议吗?
这是我的代码:

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

最佳答案

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

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,由返回0的read()指示:
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");
}

09-11 05:12