Linux下的进程间通信方式———管道

一、什么是进程间通信

进程间通信就是在不同进程之间传播或交换信息,那么不同进程之间存在着什么双方都可以访问的介质呢?进程的用户空间是互相独立的,一般而言是不能互相访问的,唯一的例外是共享内存区。但是,系统空间却是“公共场所”,所以内核显然可以提供这样的条件。除此以外,那就是双方都可以访问的外设了。在这个意义上,两个进程当然也可以通过磁盘上的普通文件交换信息,或者通过“注册表”或其它数据库中的某些表项和记录交换信息。广义上这也是进程间通信的手段,但是一般都不把这算作“进程间通信”。

二 、管道在进程间通信的方式
1、有名管道

可以在任意的两个进程中通信,写入的数据在内存中,是半双工的的操作方式。

2、无名管道

只能在父子进程间进行通信,写入的数据在内存中,是半双工的的操作方式。

3、管道的使用方法

主要有下面几种方法: 1)pipe, 创建一个管道,返回2个管道描述符.通常用于 父子进程之间通讯. 2)popen, pclose: 这种方式只返回一个管道描述符,常用于通信另一方是stdin or stdout; 3)mkpipe: 命名管道, 在许多进程之间进行交互。

4、有名管道的发送端的代码操作
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <assert.h>
int main()
{
    int fdw = open("./fifo",O_WRONLY);
    assert(fdw != -1);
    printf("fdw=%d\n",fdw);
    while(1)
    {
    printf("input:");
    char buff[128]={0};
    fgets(buff,128,stdin);
    if(strncmp(buff,"end",3)==0)
    {
        break;
    }
    write(fdw,buff,strlen(buff));
    }
    close(fdw);
    exit(0);
}
有名管道的接收端的代码操作
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <assert.h>
int main()
{
    int fdr=open("./fifo",O_RDONLY);
    assert(fdr != -1);
    while(1)
    {
        char buff[256]={0};
        int n=read(fdr,buff,255);
        if(n == 0)
        {
            break;
        }
        printf("buff[%d]=%s\n",n-1,buff);
    }
    close(fdr);
    exit(0);
}
5、无名管道的在父子进程间通信方式代码
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
    int fd[2];
    int res=pipe(fd);
    assert(res != -1);
    pid_t pid = fork();
    assert(pid != -1);
    if(pid == 0)
    {
        close(fd[1]);
        char buff[128]={0};
        read(fd[0],buff,127);
        printf("chlid=%s\n",buff);
        close(fd[0]);
    }
    else
    {
        close(fd[0]);
        write(fd[1],"hello",5);
        close(fd[1]);
    }
    exit(0);
}
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值