进程间通信(二)有名管道

有名管道FIFO依赖于文件系统,使得不仅仅是亲缘进程,同主机任意进程间也可实现通信。
有名管道和普通文件一样具有磁盘存放路径、文件权限和其他属性。
但是有名管道并没有在磁盘中存放真正的信息,他存储的通信信息在内存中,两个进程通信结束后自动消失。
通信结束后,有名管道的文件路径本身仍然存在。


API:
\*创建一个有名管道*\
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(__const char *__path,__mode_t __mode);
创建成功则返回0,否则返回0


亲缘关系进程间使用有名管道(读写时需要确定对方的存在否则阻塞):

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>

int main(){

        int pid;
        int error;
        unlink("FIFO");                         //delete FIFO
        error=mkfifo("FIFO",0777);
        if(error){
                printf("can not touch FIFO\n");
                return -1;
        }
        pid=fork();
        if(pid==0){                     //child
                int fd;
                char buf[128];
                memset(buf,'\0',128);
                fd=open("FIFO",O_RDONLY);
                close(fd);
                //read(fd,buf,10);
        }
        else{                           //father
                int fd;
                fd=open("FIFO",O_WRONLY);
                sleep(1);
                printf("to write\n");
                write(fd,"helloworld",10);
                printf("write done\n");
        }
        return 0;
}                

输出结果:
to write
(子进程阻塞在write函数)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值