您的位置:首页 > 运维架构 > Linux

Linux--进程间通信(管道及有名管道FIFO)(转)

2012-03-22 21:41 645 查看
一. 管道:

   1.只能用于具有亲缘关系的进程之间的通信  

   2.半双工通信模式

   3.一种特殊的文件,是一种只存在于内核中的读写函数

管道基于文件描述符,管道建立时,有两个文件描述符:

a. fd[0]: 固定用于读管道

b. fd[1]: 固定用于写管道

创建管道:pipe()

View Code

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

#define FIFO "myfifo"
#define BUFF_SIZE 1024

int main() {
char buff[BUFF_SIZE];
int real_read;
int fd;

%access确定文件或文件夹的访问权限。即,检查某个文件的存取方式
%如果指定的存取方式有效,则函数返回0,否则函数返回-1
%若不存在FIFO,则创建一个
if(access(FIFO,F_OK)==-1){
if((mkfifo(FIFO,0666)<0)&&(errno!=EEXIST)){
printf("Can NOT create fifo file!\n");
exit(1);
}
}

%以只读方式打开FIFO,返回文件描述符fd
if((fd=open(FIFO,O_RDONLY))==-1){
printf("Open fifo error!\n");
exit(1);
}

% 调用read将fd指向的FIFO的内容,读到buff中,并打印
while(1){
memset(buff,0,BUFF_SIZE);
if ((real_read=read(fd,buff,BUFF_SIZE))>0) {
printf("Read from pipe: '%s'.\n",buff);
}
}

close(fd);
exit(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: