【发布时间】:2020-03-27 23:48:18
【问题描述】:
我编写了一个程序,其中父进程创建了两个子进程。 父进程写入第一个或第二个子进程,而子进程读取消息。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#define MSGSIZE 64
char msgbuf[MSGSIZE];
int main(){
int p1[2];
int p2[2];
int nread;
int choice = 0;
pid_t child_a,child_b;
if(pipe(p1) == -1){
printf("error in creating pipe\n");
exit(-1);
}
if(pipe(p2) == -1){
printf("error in creating pipe\n");
exit(-1);
}
child_a = fork();
if (child_a == 0) {
dup2(p1[0], STDIN_FILENO);
read(STDIN_FILENO,msgbuf,MSGSIZE);
printf("%d receives message: %s\n",getpid(),msgbuf);
close(p1[0]);
close(p1[1]);
} else {
child_b = fork();
if (child_b == 0) {
dup2(p2[0], STDIN_FILENO);
read(STDIN_FILENO,msgbuf,MSGSIZE);
printf("%d receives message: %s\n",getpid(),msgbuf);
close(p2[0]);
close(p2[1]);
} else {
/* Parent Code */
// Write something to child A
while(1){
printf("<child_to_receive_msg> <message>\n");
scanf("%d %s",&choice,msgbuf);
switch(choice){
case 1:
usleep(250);
write(p1[1], msgbuf, MSGSIZE);
break;
// Write something to child B
case 2:
usleep(250);
write(p2[1], msgbuf, MSGSIZE);
break;
case -1:
usleep(250);
printf("parent waiting");
wait(NULL);
exit(-1);
break;
}
}
}
}
return 0;
}
我的问题是我希望父进程继续写入子进程。使用上面的代码,一旦它写入子进程或子进程 2,它就不会再次写入,或者至少子进程不会再次读取它。我不知道是否可以这样做。
我尝试将 while 循环放在程序的开头,但这会导致每次都创建另一个子进程。
【问题讨论】:
-
父进程正在执行多次写入,但子进程仅执行一次读取。子进程代码中也需要循环。
-
为什么在整个代码中都有
usleep调用?应该不需要。 -
为什么要复制文件句柄?恕我直言,您无需复制文件句柄,无论如何,这些句柄都是在 fork 上“复制”的(我认为是引用)。只需使用它们在每个子项中读取或写入并关闭它们而无需重复。