【发布时间】:2015-06-23 04:24:34
【问题描述】:
我正在尝试从子进程向父进程发送十条消息。但是程序的输出显示父进程只读取了第一条和第六条消息。我尝试更改代码中的 sleep() 位置,也尝试使用 while() 而不是 for() 读取,但问题仍然存在。 代码如下:
int main(int argc, char *argv[]){
char ch, message_from_A[100], message_from_B[100], msg_to_log[100], msg_to_B[100];
int i, x, fd_log[2], fd_A_B[2], fd_B_C[2], fd_B_D[2];
pipe(fd_log);
//fork process A
if (fork()==0) { //child
printf("Inside process A\n");
for (i=0; i < 10; i++) {
//creat new msg
x = (rand() % 2);
if (x == 1)
ch='C';
else
ch='D';
//write msg to log pipe
sprintf(msg_to_log, "A sent to B: %c %d\n", ch, i);
printf("wirtten to log pipe--> %s\n", msg_to_log);
close(fd_log[READ]);
write(fd_log[WRITE], msg_to_log, strlen(msg_to_log)+1);
}//end for()
close(fd_log[WRITE]); //this line won't affect output
_exit(1);
} else { //parent
printf("Inside process log\n");
close(fd_log[WRITE]);
while ( read(fd_log[READ], message_from_A, 100) > 0 ) {
sleep(1);
printf("\nmsg from A: %s", message_from_A);
}
close(fd_log[READ]); //this line won't affect output
}}
此程序的输出显示父级仅读取第一条和第六条消息!这是输出:
内部进程日志
进程A内部
写入日志管道--> A 发送到 B: C 0
写入日志管道--> A 发送到 B: C 1
写入日志管道--> A 发送到 B: C 2
写入日志管道--> A 发送到 B: D 3
写入日志管道--> A 发送到 B: D 4
写入日志管道--> A 发送到 B: D 5
写入日志管道--> A 发送到 B: D 6
写入日志管道--> A 发送到 B: D 7
写入日志管道--> A 发送到 B:C 8
写入日志管道--> A 发送到 B: C 9
来自A的消息:A发送到B:C 0
来自 A: B: D 5 的消息
感谢任何想法或建议。
【问题讨论】:
标签: c process fork parent-child