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

Linux c==进程通信--有名管道(4)

2016-10-25 21:40 393 查看
命名管道和无名管道基本相同,但也有不同点:

无名管道只能由父子进程使用;

但是通过命名管道,不相关的进程也能交换数据。

命名管道的使用

创建管道mkfifo

打开管道open

读管道read

写管道write

关闭管道close

删除管道unlink

函数mkfifo

函数作用:创建有名管道

函数原型:int mkfifo(const char * pathname, mode_t mode);

函数参数:pathname:有名管道的路径,文件名 mode:属性(创建时,该文件必须不存在)

返回值 :成功返回0,出错:-1

头文件 :

#include<sys/types.h>

#include<sys/stat.h>


函数unlink

函数作用:删除文件

函数原型:int unlink(const char * pathname);

函数参数:pathname : 文件路径+文件名

返回值 :成功 : 0;出错:-1

头文件 :

#include<unistd.h>
Fifo_wr.c

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO_SERVER "/tmp/myfifo"

main(int argc,char** argv)
{
int fd;
char w_buf[100];
int nwrite;

/*打开管道*/
fd = open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);

if(argc == 1)
{
printf("Please send something\n");
exit(-1);
}

strcpy(w_buf,argv[1]);

/* 向管道写入数据 */
nwrite = write(fd,w_buf,100);
if( nwrite== -1)
{
printf("The FIFO has not been read yet.Please try later\n");
}
else
printf("write %s to the FIFO\n",w_buf);
}

Fifo_rd.c

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

#define FIFO "/tmp/myfifo"

main(int argc,char** argv)
{
char buf_r[100];
int  fd;
int  nread;

/* 创建管道 */    //读写操作中只需要有一个文件中创建有名管道
if((mkfifo(FIFO,O_CREAT|O_EXCL) < 0) && (errno != EEXIST))
printf("cannot create fifoserver\n");

printf("Preparing for reading bytes...\n");

memset(buf_r,0,sizeof(buf_r));

/* 打开管道 */
fd = open(FIFO,O_RDONLY|O_NONBLOCK,0);
if(fd == -1)
{
perror("open");
exit(1);
}
while(1)
{
memset(buf_r,0,sizeof(buf_r));

nread = read(fd,buf_r,100);
if(nread == -1)
{
if(errno == EAGAIN)
printf("no data yet\n");
}
printf("read %s from FIFO\n",buf_r);
sleep(1);
}
pause(); /*暂停,等待信号*/
unlink(FIFO); //删除文件
}


FIFO文件在使用上和普通文件有相似之处,但是也有不有

不同之处:

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

2. 写fifo文件的进程只能以”WRONLY”方式打开fifo

3. fifo文件里面的内容被读取后,就消失了。但是普通文件里面的内容读取后还存在。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux 通信