gpt4 book ai didi

C fork 两个子进程并在父进程和子进程之间使用管道

转载 作者:行者123 更新时间:2023-11-30 17:52:03 26 4
gpt4 key购买 nike

我正在尝试 fork 两个 child 。父级读取发送到管道的行。子进程 1 读取它并将其写入另一个管道,最后子进程 2 读取它。但是,输出始终是父获取行。谢谢!

#define MAX 80

void child();
void parent();
void childtwo();
char * getli();
void printline(char *buffer, int count);
char * convertCase(char *str);

int pipe1[2];
int pipe2[2];
int main(int argc, char **argv)
{
pipe(pipe1);
pipe(pipe2);
if(fork()){
if(fork()){
printf("1st\n");
parent();
exit(0);
}
else{
printf("3rd\n");
childtwo();
exit(0);
}
}
else{
printf("2nd\n");
child();
exit(0);
}
}

void child(){
char *buf;
int count = 0;
close(pipe1[1]);
close(pipe2[0]);
while(1){
buf = (char *) malloc(sizeof(char)*MAX);
read(pipe1[0], buf, MAX);
if (strcmp(buf,"quit")== 0){
printf("Child is leaving\n");
free(buf);
break;
}
else{
printf("Child: ");
printline(buf,strlen(buf));
write(pipe2[1],buf, strlen(buf)+1);
free(buf);
}
close(pipe2[1]);
close(pipe1[0]);
exit(0);
}
}

void childtwo()
{
char *buf;
int count = 0;
close(pipe2[1]);
buf = (char *) malloc(sizeof(char)*MAX);
while(1){
buf = (char *) malloc(sizeof(char)*MAX);
read(pipe2[0], buf, MAX);
if (strcmp(buf,"quit")== 0){
printf("Childtwo is leaving\n");
free(buf);
break;
}
else{
printf("Childtwo:");
printline(buf,strlen(buf));
free(buf);
}
}
close(pipe2[0]);
exit(0);
}

void parent(){
char * buffer;
int count = 0, done=0;
close(pipe1[0]);
while (done != 1){
printf("parent getting line: ");
buffer = getli();
write(pipe1[1],buffer, strlen(buffer)+1);
if (strcmp(buffer,"quit")== 0){
puts("parent goes away");
free(buffer);
break;
}
free(buffer);
}
close(pipe1[1]);
exit(0);
}

最佳答案

我的猜测是,它对于第一行工作正常,但对于其他任何行都不起作用。

这是因为第一个子进程(在 child 函数中)在读取其输入后退出。您可能打算将 closeexit 调用放在循环之外。

关于C fork 两个子进程并在父进程和子进程之间使用管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16380276/

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