两个孩子从pipe道上读书

这是我想要做的:

我试图创build一个程序,创build父母与两个孩子,父母创build一个未命名的pipe道,写入它和孩子们应该从它读取(每1字节),然后输出结果在两个不同的terminal窗口。 我不知道的是如何同步它们。

我在一个terminal窗口中得到了这样的东西:Nejke aa和第二个:我想要的是:Nejake数据

我试图在互联网上search,但我仍然问。 任何帮助是极大的赞赏。

#include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <sys/stat.h> /* declare our procedures */ void runchild1(int pfd[]); void runchild2(int pfd[]); /* some data to write and read from pipe */ const char some_data[] = "Nejake data" ; int main(int argc, char **argv) { int pid, status; //PID for debugging int fd[2]; //file descriptors for the pipe /* let create some pipe */ pipe(fd); /* supposed to run two children of the process */ runchild1(fd); runchild2(fd); /* this is important! close both file descriptors on the pipe */ close(fd[0]); close(fd[1]); /* pick up all the dead children */ while ((pid = wait(&status)) != -1) fprintf(stderr, "process %d exits with %d\n", pid, WEXITSTATUS(status)); exit(0); } void runchild1(int pfd[]) /* run the first child */ { int pid; /* you may want to print it for debugging */ int data_processed; /* store data */ int des; /* descriptor for open files */ char buffer; /* buffer for reading byte of data */ switch (pid = fork()) { case 0: /* child reads from the pipe */ close(pfd[1]); /* this process don't need the other end */ while ((data_processed = read(pfd[0],&buffer,1)) > 0) { printf("Proces %d, data citane po bajte: %c\n",getpid(),buffer); des = open("/dev/ttys001",O_RDWR); write(des, &buffer,1); } exit(0); default: /* parent writes to the pipe */ /* write some data for children to read */ data_processed = write(pfd[1], some_data, strlen(some_data)); printf("Zapis %d bytov cez nepomenovanu ruru:\n", data_processed); printf("Zapisane: %s\n",some_data); printf("Som rodic dvoch deti: %d\n",getpid()); break; case -1: perror("fork"); exit(1); } } void runchild2(int pfd[]) /* run the second child */ { int pid; int data_processed; int des; char buffer; switch (pid = fork()) { case 0: /* child */ close(pfd[1]); /* this process doesn't need the other end */ while ((data_processed = read(pfd[0],&buffer,1)) > 0) { printf("Proces %d, data citane po bajte: %c\n",getpid(),buffer); des = open("/dev/ttys002",O_RDWR); write(des, &buffer,1); } exit(0); default: /* parent does nothing */ break; case -1: perror("fork"); exit(1); } } 

如果两个孩子都需要看到相同的数据,则需要两个管道,每个孩子一个,父母必须在每个管道上写入每个消息两次。

或者,你可以使用进程替换来运行tee命令,或者你可以查找(尝试查找)程序peetee进程/管道变体) – 或者你可以关注这个Stack Overflow答案中的链接。 你的节目将有一个管道,但是孩子们最终会有自己的管道。

Unix管道是FIFO。 一个输入,一个输出。 没有什么像一个管道的两个输出。 您的秘籍是: System V IPC关键字和ipcs命令。