[国嵌攻略][081][有名管道通讯]

有名管道

有名管道又称为FIFO文件,因此我们对有名管道的操作可以采用文件操作的方法,如使用open,read,write等。

 

FIFO文件的特点

1.读取FIFO文件的进程只能以RDONLY方式打开FIFO文件。

2.写入FIFO文件的进程只能以WRONLY方式打开FIFO文件。

3.FIFO文件里面的内容被读取后就消失了,但普通文件里面的内容被读取后还存在。

 

wFIFO.c

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

void main(){
    //创建管道
    mkfifo("fifo", 0777);
    
    //打开管道
    int fd;
    
    fd = open("fifo", O_WRONLY);
    
    //写入数据
    char buf[13] = "hello world!";
    
    write(fd, buf, 13);
    
    //关闭管道
    close(fd);
}

 

rFIFO.c

#include <stdio.h>

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

void main(){
    //打开管道
    int fd;
    
    fd = open("fifo", O_RDONLY);
    
    //读取数据
    char buf[13];
    
    read(fd, buf, 13);
    
    //显示数据
    printf("%s\n", buf);
    
    //关闭管道
    close(fd);
    
    //删除管道
    unlink("fifo");
}

 

posted @ 2016-02-28 10:34  盛夏夜  阅读(323)  评论(0编辑  收藏  举报