进程通信之有名管道

1、无名管道只能用于有亲缘关于的进程通信,有名管道可以实现无亲缘关系的通信

2、有名管道fifo 给文件系统提供一个路径,这个路径和管道关联,只要知道这个管道路径,就可以进行文件访问,fifo 

是指先进先出,也就是先写入的数据,先读出来

3、有名管道的读写速度非常快

4、man 3 mkfifo

5、int mkfifo(const char *pathname, mode_t mode)
     –参数*pathname:路径名,管道名称
     –参数mode:管道的权限
     –返回值:成功返回0,错误返回-1
并更改errno的值。errno有可能出现的值为EACCESS EEXIST ENAMETOO-LONG ENOENT ENOENT ENOSPE ENOTDIR EROFS

例:

1、创建管道

	
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
int main (int argc, char *argv[])
{
    mode_t mode = 0666; /*新创建的FIFO模式*/
    if(argc != 2) {
        printf( "USEMS: create_fifo {fifoname}\n");
	exit(1);
    }
    /*使用mkfifo()函数创建一个FIFO管道*/
    if((mkfifo(argv[1],mode)) < 0) {
        perror("fail to mkfifo");
        exit(1);
    }else{
        printf("you successfully create a FIFO name is:%s\n",argv[1]);
    }
        exit(1);
}


2、FIFO 的读写操作

open函数参数flag标志位的O_NONBLOCK标志,它关系到函数的返回状态。
O_NONBLOCK 
置位: 只读open立即返回。当只写open时,如果没有进程为读打开FIFO,则返回-1,并置errno值为ENXIO
不置位:open视情况阻塞。只读open要阻塞到进程为写打开FIFO,只写open要阻塞到有进程为读打开FIFO。

write_fifo.c

#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<limits.h>
#define BUFSZ PIPE_BUF
	
int main(void)
{
    int fd;
    int n,i;
    char buf[BUFSZ];
    time_t tp;
    printf("I am %d\n",getpid());
    if((fd = open("fifo1",O_WRONLY)) < 0 {
         perror("open");
         exit(1);
    }
    for(i = 0; i<10; i++) {
         time(&tp);
         n = sprintf(buf, "write_fifo %d sends %d", getpid(),ctime(&tp));
         printf("send msg: %s\n",buf);
         if((write(fd,buf,n+1)) < 0) {
               perror("wrinte");
               close(fd);
               exit(1);
         } 
         sleep(3);
     }
     close(fd);
     exit(0);
}


read_fifo.c

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<limits.h>
	
#define BUFSZ PIPE_BUF
int main(void)
{
     int fd;
     int n,i;
     char buf[BUFSZ];
     mode_t mode = 0666;
     if((fd = open("fifo1",O_RDONLY)) < 0 {
         perror("open");
         exit(1);
     }
     while((len = read(fd,buf,BUFSZ)) > 0);
         printf("read_fifo read :%s",buf);
     close(fd);
     exit(0);
}

$gcc write_fifo.c -o write_fifo
$gcc read_fifo.c -o read_fifo

$mkfifo -m 666 fifo1
$./write_fifo
I am 16414
Send msg :write_fifo 16414 sends Fri Mar 22 15:48:54 2013

$./read_fifo
read_fifo read:write_fifo 16414 sends Fri Mar 22 15:48:54 2013


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值