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

【linux】——进程间的通信之管道通信

2013-06-10 15:33 441 查看
通过创建命名管道实现任何一个进程的通信:

mkfifo_read.c

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

#include<fcntl.h>
#include<stdlib.h>

#define FIFO "text"

int main(int argc, char *argv[])
{
int fd;
int mkfi;
int fd_read;
char buf[100];

if(mkfifo(FIFO,O_CREAT|O_EXCL) < 0)
{
printf("mkfifo error!\n");
exit(1);
}
if((fd = open(FIFO,O_RDONLY|O_NONBLOCK,0)) == -1)
{
printf("open fifo error!\n");
exit(1);
}
while(1)
{
memset(buf,0,sizeof(buf));
if(fd_read = read(fd,buf,100) == -1)
printf("this is no data!\n");
else
printf("%s\n",buf);
sleep(1);
}
}


mkfifo_write.c

#include<stdio.h>
#include<stdlib.h>

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

#define FIFO "text"

int main(int argc, char *argv[])
{
int fd;
int nwrite;
if((fd = open(FIFO,O_WRONLY|O_NONBLOCK,0)) == -1)
{
printf("open FIFO error!\n");
exit(1);
}

if((nwrite = write(fd,argv[1],100)) == -1)
{
printf("error!\n");
}
else
printf("write %s\n",argv[1]);
}


注:

一:O_NONBLOCK 如果pathname指的是一个FIFO、一个特殊文件或一个字符特殊文件,则此选项为文件的本次打开操作和后续的I/O操作设置非阻塞模式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: