linux应用编程--命名管道

来源:互联网 发布:淘宝手机流量互刷 编辑:程序博客网 时间:2024/05/17 06:19

      上一章介绍了无名管道pipe的应用,但是无名管道的通信有一个缺点:就是这些进程都由一个共同的祖先进程启动,这给我们在不相关的的进程之间交换数据带来了不方便。这里将会介绍进程的另一种通信方式——命名管道,来解决不相关进程间的通信问题。

   命名管道也被称为FIFO文件,它是一种特殊类型的文件,它在文件系统中以文件名的形式存在(下面的实例中当前目录下创建myfifo的命名管道成功之后,可以在当前目录下找到一个myfifo的文件夹),但是它的行为与pipe类似。由于Linux中所有的事物都可被视为文件,所以对命名管道的使用也就变得与文件操作非常的统一,也使它的使用非常方便,同时我们也可以像平常的文件名一样在命令中使用。

        接下来介绍一个实例来讲解怎么使用命名管道,分别打开两个进程,一个进程用于从管道读取数据,另一个进程从管道写入数据。

程序1:读数据

#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 "myfifo"
int main(int argc,char** argv)
{
char buf_r[100];
int  fd;
int  nread;

/* 创建管道 */
if((mkfifo(FIFO,0777)<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,0);
if(fd==-1)
{
perror("open");
exit(1);
}
while(1)
{
memset(buf_r,0,sizeof(buf_r));

if((nread=read(fd,buf_r,100))==-1)
{
if(errno==EAGAIN)
printf("no data yet\n");
}
printf("read %s from FIFO\n",buf_r);
sleep(1);
}
        close(fd);
        printf("hello\n");
        unlink(FIFO); //删除文件
        return 0;//这一段代码都不执行,一直在while循环里面,之前用于测试unlink函数                        //使用
}

程序2:写程序

#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 "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]);

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

程序解析:

1.首先要执行fifo_read1的文件,执行结束之后,利用ls的命令,可以看到一个myfifo的文件,如下图所示:


2.读数据的进程中,是以阻塞的方式打开,所以程序会一直等,等到另外一个进程通过管道发送数据过来


3.执行fifo_write,并传入你要发送的数据,此时可以看到刚才的程序开始往下走了



4.想要使用不阻塞的情况,可以打开管道的时候设置为不阻塞

fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);

原创粉丝点击