C语言中的fork和pipe的问题

Python020

C语言中的fork和pipe的问题,第1张

fork ----->fork ----->fork

加入进程A fork出了进程B,然后进程B又fork出了进程C,进程C又fork出了进程D

pipe是管道,只有一个入口,一个出口。可以把入口和出口分别放到父子进程中。

父进程负责读,子进程负责写。或者子进程读,父进程写。

你的例子里,在进程A里创建管道PipeA,然后fork出进程B。进程AB之间使用PipeA通信。

进程B再创建PipeB,然后进程BC之间使用PipeB通信。

进程C再创建PipeC,然后进程CD之间使用PipeC通信。

如果想把进程A的数据传递给进程D,那么应该:进程A向PipeA写入数据,进程B从PipeA中读取数据,然后再写入PipeB,进程C从PipeB中读取数据,然后再写入PipeC,进程D从PipeC中读取数据

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <assert.h>

int main(int argc,char *argv[])

{

int pd[2]/*用于保存管道文件描述符*/

char out[80],str[]="safasfsa"/*str是要写入的字符串,out用于保存从管道读取的字符串*/

assert(pipe(pd)!=-1)/*断言用于确定pipe()函数执行成功,如果管道创建失败,则pipe()返回-1*/

if (!fork()) write(pd[1],str,strlen(str))/*创建子进程,并将字符串写入管道*/

else {

read(pd[0],out,strlen(str))/*在主进程中从管道中读取子进程写入的字符串*/

printf("%s\n",out)/*主进程中输出。*/

}

return 0

}

#include <stdio.h>

#include <unistd.h>

#include <string.h>

int main(int argc, const char *argv[])

{

    int fd[2]

    int pid

    if (argc != 2)

    {

        printf("Usage:\n\t%s string\n", argv[0])

        return 1

    }

    if (pipe(fd) < 0)

    {

        printf("Unable to create pipe!\n")

        return 1

    }

    // fork child process

    pid = fork()

    if (pid == 0) //child

    {

        close(fd[0]) //close read end

        write(fd[1], argv[1], strlen(argv[1])) //write message

        close(fd[1]) //close before exit

    }

    else if (pid > 0) //parent

    {

        char buf[1024]

        int len

        close(fd[1]) //close write end

        len = read(fd[0], buf, sizeof(buf)) //read from the pipe

        buf[len] ='\0'

        printf("<PARENT> message from child: %s\n", buf)

        wait(NULL) //wait for child exit

        close(fd[0]) //close before exit

    }

    else

    {

        printf("Unable to fork!\n")

        return 1

    }

    return 0

}