C 为什么不是';t pipe()在并行子进程之间分叉两次后是否工作?

C 为什么不是';t pipe()在并行子进程之间分叉两次后是否工作?,c,string,unix,pipe,fork,C,String,Unix,Pipe,Fork,我的目标是将字符串从一个子进程发送到另一个子进程。我在父进程中设置了一个管道,然后fork两次。两个到达语句都打印,为什么管道消息不打印 #include<stdlib.h> #include<stdio.h> #include<unistd.h> #include<sys/wait.h> #include<sys/types.h> #include<string.h> int main (char * argv[], in

我的目标是将字符串从一个子进程发送到另一个子进程。我在父进程中设置了一个管道,然后fork两次。两个到达语句都打印,为什么管道消息不打印

#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
int main(字符*argv[],int argc)
{
int-arr[2];
管道(arr);
int id=0;
int-pid=fork();
id=1;
如果(pid>0)pid=fork();
如果(pid>0)
{
关闭(arr[0]);
关闭(arr[1]);
等待(空);
}
else if(id==0)
{
关闭(arr[0]);
字符消息[]=“超文本传输\n”;
写入(arr[1],消息,strlen(消息)+1);
printf(“已到达\n”);
}
else if(id==1)
{
printf(“已到达\n”);
关闭(arr[1]);
char*buf=malloc(sizeof(char)*20);
读取(arr[0],buf,20);
printf(“%s”,buf);
}
返回0;
}

程序输出“达到”两次。

对于所有进程,id为1。如果(id==0)写入任何内容,则不会进入else,因此,您正在尝试从空管道中读取。

您的问题是,对于两个子进程,
id=1
。实际上,两个子进程都执行行
id=1
,因此它们都是接收者

尝试:

#包括
#包括
#包括
#包括
#包括
#包括
int main(字符*argv[],int argc)
{
int-arr[2];
管道(arr);
int id=0;
int-pid=fork();
如果(pid>0){
pid=fork();
id=1;//这里只有第二个子进程(和父进程,但谁在乎呢)的id==1。
}
如果(pid>0)
{
关闭(arr[0]);
关闭(arr[1]);
等待(空);
}
else if(id==0)
{
关闭(arr[0]);
字符消息[]=“超文本传输\n”;
写入(arr[1],消息,strlen(消息)+1);
printf(“已到达\n”);
}
else if(id==1)
{
printf(“已到达\n”);
关闭(arr[1]);
char*buf=malloc(sizeof(char)*20);
读取(arr[0],buf,20);
printf(“%s”,buf);
}
返回0;
}

id对于所有进程都是1。如果(id==0)写入任何内容,则不能进入
else。id=1
应位于
if(pid>0)
内,因此在第一个子项中不会为真。是否确实如此?我应该两次澄清“达到”的程序输出。您是正确的,我将在达到冷却时间后接受此答案。
#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();

if(pid > 0) {
    pid = fork();
    id = 1; // Here only the second child process (and the parent process, but who cares) have id == 1.
}

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