Linux进程通信方法--管道

1 pipe

#include <unistd.h>
int pipe(int filedes[2]);

只能用以父子进程之间进行通信。注意,pfd[0]只能read,pfd[1]只能write.是一个单向的。


2 fifo 即命名管道

#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);

mkfifo() 用法和creat用法相同,创建出一个虚拟的文件,可以在没有关系的进程之间进行共享,传递信息。创建好之后就可以像对待一个文件一样使用它。
注意在非阻塞模式下,write only的打开会直到有read only的open发生时,才会返回。反之read only的open直到write only的open发生时才会返回。在阻塞模式下,read only的open会立刻返回,但是write only的open,在没有为读而打开的情况下会返回1,errno会被置为ENXIO。

示例:

//先执行的进程

#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

int main()
{
    int fd = 0;
    if(mkfifo("fifo.tmp",S_IRUSR | S_IWUSR) < 0)
        perror("mkfifo failed!");

    if((fd = open("fifo.tmp",O_WRONLY)) <= 0 )  
        perror("error open fifo");

    if(write(fd,"hello",6) != 6)
        perror("error write");

    close(fd);
    return 0;
}

//后执行的进程

#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

int main()
{
    int fd = 0;
    char buf[32];

    if((fd = open("fifo.tmp",O_RDONLY)) <= 0 )  
        perror("error open fifo");

    if(read(fd,buf,sizeof(buf)) <= 0)
        perror("error read");

    printf("read %s/n",buf);

    close(fd);
    return 0;
}

第一个程序先运行会阻塞,直到第二个程序运行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值