gpt4 book ai didi

c - 两个 child 用 pipe 读书

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:55 26 4
gpt4 key购买 nike

这是我想做的:

我试图制作一个程序来创建带有两个 child 的父级,父级创建未命名的管道,写入其中,子级应该从中读取(每 1 个字节),然后在两个不同的终端窗口中输出结果.我不知道如何同步它们。

我在一个终端窗口中得到类似这样的信息:Nejke aa在第二个中:adt我要:Nejake 数据

我尝试在互联网上搜索,但我还是要问。非常感谢任何帮助。

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

最佳答案

如果两个 child 都需要查看相同的数据,您将需要两个管道,每个 child 一个,并且父级必须将每条消息写入两次,每个管道一次。

或者,您可以运行 tee使用 process substitution 命令,或者您可以查找(尝试查找)程序 pee(tee 的进程/管道变体)— 或者您可以点击此 Stack Overflow answer 中的链接.您的程序将有一个管道,但每个 child 最终都会有自己的管道。

关于c - 两个 child 用 pipe 读书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15731790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com