无名管道的通信

通过使用管道实现两个或多个进程之间的通信。所谓管道,就是将一个进程的标准输出与另一个进程的标准输入联系在一起,进行通信的一种方法。同组进程之间可用无名管道任意通信,而不同组进程之间可通古共有名管道进行通信。

使用无名管道pipe(),进行父子进程之间的通信。

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
int pipe(int filedes[2]);
char parent[] = "A message to pipe's communication.\n";
int main()
{
    int pid;
    int chanl[2];
    char buf[100];
    pipe(chanl);
    pid = fork();
    if(pid < 0)
    {
        printf("to creat child error\n");
        exit(1);
    }
    if(pid > 0)
    {
        close(chanl[0]);
        printf("parent process sends a message to child.\n");
        write(chanl[1],parent,sizeof(parent));
        close(chanl[1]);
        printf("parent process waits the child to terminate.\n");
        wait(0);
        printf("parent process terminate.\n");
        
    }
    else
    {
        close(chanl[1]);
        read(chanl[0],buf,100);
        printf("The message read by child process from parent is :%s.\n",buf);
        close(chanl[0]);
        printf("child process terminates\n");
    }
    return 0;
}


 

分析:父进程首先使用pipe(chanl)系统调用打开一个无名管道,之后创建一个子进程。子进程复制父进程的打开文件表。为了正确通信,父进程关闭读通道close(chanl[0]),子进程关闭写通道close(chanl[1]).父进程向管道写,子进程从管道读。完成一次通信后,父子进程分别关闭自己的读/写通道,管道文件消失。

PS:使用无名管道进行通信时,是使用临时文件的方式实现进程之间的批量数据传输。若通信双方不是父子关系,不能直接建立通信联系,而要有创建他们的共同的父进程为他们创建管道。在通过复制父进程映像使两者之间建立联系

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值