进程的通信—管道通信

在父进程中用 pipe()建立一条管道线,往管道里写一句话,两个子进程接收这句话。

//已经被读取的数据在管道内不再存在,这意味着数据在管道中不能重复利用
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<signal.h>
#include<unistd.h>
int pid1,pid2;
int main()
{
    int fd[2];
    char OutPipe[100],InPipe[100];
    pipe(fd);
    while((pid1=fork())==-1);
    if(pid1==0)
    {
        lockf(fd[0],1,0);
        read(fd[0],InPipe,50);
        printf("%s\n",InPipe);
        lockf(fd[0],1,0);
        lockf(fd[1],1,0);
        write(fd[1],InPipe,50);//将管道中的内容重新写回
        lockf(fd[1],1,0);
        exit(0);
    }
    else
    {
            while((pid2=fork())==-1);
            if(pid2==0)
            {
                lockf(fd[0],1,0);
                read(fd[0],InPipe,50);
                printf("%s\n",InPipe);
                lockf(fd[0],1,0);
                lockf(fd[1],1,0);
                write(fd[1],InPipe,50);//将管道中内容重新写回
                lockf(fd[1],1,0);
                exit(0);
            }
            else
            {
                lockf(fd[1],1,0);//fd[1]为互斥信号量
                sprintf(OutPipe,"father process is sending message to children!");
                write(fd[1],OutPipe,50);
                lockf(fd[1],0,0);
                wait(0);
                wait(0);
                exit(0);
            }
    }
    return 0;
}

分析代码:

已经被读取的数据在管道内不再存在,这意味着数据在管道中不能重复利用,所以在其中一个子进程中将从父进程接收到的字符串重新发回到管道中。

 

posted @ 2017-11-03 21:24  奇热行  阅读(360)  评论(0)    收藏  举报