【发布时间】:2018-01-29 18:06:50
【问题描述】:
我的目标是将字符串从一个子进程发送到另一个子进程。我在父进程中设置了一个管道,然后分叉了两次。两个到达的语句都打印了,为什么管道消息没有?
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>
int main (char * argv[], int argc)
{
int arr[2];
pipe(arr);
int id = 0;
int pid = fork();
id = 1;
if(pid > 0) pid = fork();
if(pid > 0)
{
close(arr[0]);
close(arr[1]);
wait(NULL);
}
else if (id == 0)
{
close(arr[0]);
char message[] = "HYPERTEXT TRANSFER\n";
write(arr[1],message,strlen(message)+1);
printf("reached\n");
}
else if(id == 1)
{
printf("reached\n");
close(arr[1]);
char * buf = malloc (sizeof(char)* 20);
read(arr[0], buf, 20);
printf("%s", buf);
}
return 0;
}
程序输出“reached”两次。
【问题讨论】:
-
id 对于所有进程都是 1。你不会进入
else if (id == 0)写任何东西。 -
id = 1应该在if (pid > 0)内,因此第一个孩子不会是这样。