2011-05-26 18:33 有名管道通信原理及系统调用mkfifo()的使用方法

来源:互联网 发布:淘宝网店推广培训 编辑:程序博客网 时间:2024/05/16 19:44

1.有名管道通信机制

2.mkfifo使用方法及实例

mkfifo函数的使用方法
[code]mkfifo(建立实名管道)
相关函数
pipe,popen,open,umask
表头文件
       #include <sys/types.h>
       #include <sys/stat.h>
定义函数
int mkfifo(const char * pathname,mode_t mode);
函数说明
mkfifo()会依参数pathname建立特殊的FIFO文件,该文件必须不存在,而参数mode为该文件的权限(mode%~umask),因此 umask值也会影响到FIFO文件的权限。Mkfifo()建立的FIFO文件其他进程都可以用读写一般文件的方式存取。当使用open()来打开 FIFO文件时,O_NONBLOCK旗标会有影响
1、当使用O_NONBLOCK 旗标时,打开FIFO 文件来读取的操作会立刻返回,但是若还没有其他进程打开FIFO 文件来读取,则写入的操作会返回ENXIO 错误代码。
2、没有使用O_NONBLOCK 旗标时,打开FIFO 来读取的操作会等到其他进程打开FIFO文件来写入才正常返回。同样地,打开FIFO文件来写入的操作会等到其他进程打开FIFO 文件来读取后才正常返回。
返回值
若成功则返回0,否则返回-1,错误原因存于errno中。
错误代码
EACCESS 参数pathname所指定的目录路径无可执行的权限
EEXIST 参数pathname所指定的文件已存在。
ENAMETOOLONG 参数pathname的路径名称太长。
ENOENT 参数pathname包含的目录不存在
ENOSPC 文件系统的剩余空间不足
ENOTDIR 参数pathname路径中的目录存在但却非真正的目录。
EROFS 参数pathname指定的文件存在于只读文件系统内。

 

在程序中使用有名管道的过程大致是这样三个步骤:

1)使用fifo()系统调用创建管道并判断是否成功及作相应的错误处理;

2)使用open()系统调用打开有名管道,并设置管道的工作模式,获取文件操作句柄fd=open()

3)使用read()或write()系统调用对对管道(文件)进行读写操作。

 

3.示例代码:

 /* fileName:fifo1.c*/

#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
 
 
#define FIFO_SERVER "/tmp/fifo"
#define OPENMODE O_WRONLY|O_NONBLOCK
 
int main(int arc,char **argv)
{
        time_t rawtime;
        int fd;
        int nwrite;
        char buf[100];
        if((mkfifo(FIFO_SERVER,O_CREAT|O_NONBLOCK|O_RDWR)<0)&&errno!=EEXIST)
                {printf("failed in create fifo server\n");
                exit(1);}
        if((fd=open(FIFO_SERVER,OPENMODE))<0)
        {
                perror("open");
 
                exit(2);
        }
        while(1)
        {
                bzero(buf,100);
                time(&rawtime);
                sprintf(buf,"The current local time is :%s\n",ctime(&rawtime));
 
                if(write(fd,buf,strlen(buf))<0)
                {
                        if(errno==EAGAIN)
                                printf("The FIFO has not been read yet,please try later\n");
                        else
                                exit(3);
                }
                printf("put %s to the fifo\n",buf);
                sleep(1);
        }
        return 0;
}

 /*filename:fifo2.c*/

  #include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
 
#define FIFO_SERVER "/tmp/fifo"
#define OPEN_MODE O_RDONLY|O_NONBLOCK
#define FIFO_MODE O_CREAT|O_RDWR|O_NONBLOCK
 
int main()
{
        char buf_r[100];
        int fd;
        int nread;
        int res;
 
        if(((res=mkfifo(FIFO_SERVER,FIFO_MODE))<0)&&errno!=EEXIST)
        {
                printf("error,failed to creat fifoserver\n%d:errno:\n",res,errno);
                exit(1);
        }
        if((fd=open(FIFO_SERVER,OPEN_MODE))<0)
        {
                printf("error in openning fifo server\n");
                exit(2);
        }
 
        while(1)
        {
                bzero(buf_r,100);
                if((nread=read(fd,buf_r,sizeof(buf_r)))<0)
                {
                        printf("error in reading from fifo_server,ready to exit\n");
                        exit(3);
                }
                else if((nread<0)&&(errno==EAGAIN))
                        printf("no data yet\n");
                else if(nread>0)
                {
                        printf("read from fifo_server:%s\n",buf_r);
                }
                sleep(1);
 
        }
        unlink(FIFO_SERVER);
        return 0;
}

编译运行结果:

先在其中一个终端窗口中运行命令fifo1,然后再在另一个终端窗口中运行fifo2.

[root@BC fifo]# fifo1
put The current local time is :Thu May 26 21:47:59 2011
 
 to the fifo
put The current local time is :Thu May 26 21:48:00 2011
 
 to the fifo
put The current local time is :Thu May 26 21:48:01 2011
 
 to the fifo
put The current local time is :Thu May 26 21:48:02 2011
 
 to the fifo
put The current local time is :Thu May 26 21:48:03 2011
 
 to the fifo
put The current local time is :Thu May 26 21:48:04 2011
 
 to the fifo
put The current local time is :Thu May 26 21:48:05 2011
 
 to the fifo
put The current local time is :Thu May 26 21:48:06 2011
 
 to the fifo
put The current local time is :Thu May 26 21:48:07 2011
 
 to the fifo

 

另一个终端窗口中的运行情况:

[root@BC fifo]# fifo2
read from fifo_server:The current local time is :Thu May 26 21:47:59 2011
 
 
read from fifo_server:The current local time is :Thu May 26 21:48:00 2011
 
 
read from fifo_server:The current local time is :Thu May 26 21:48:01 2011
 
 
read from fifo_server:The current local time is :Thu May 26 21:48:02 2011
 
 
read from fifo_server:The current local time is :Thu May 26 21:48:03 2011
 
 
read from fifo_server:The current local time is :Thu May 26 21:48:04 2011
 
 
read from fifo_server:The current local time is :Thu May 26 21:48:05 2011
 
 
read from fifo_server:The current local time is :Thu May 26 21:48:06 2011
 
 
read from fifo_server:The current local time is :Thu May 26 21:48:07 2011

 

有名管道的用法

作者:曾宏安,华清远见嵌入式学院讲师。

有名管道又称为FIFO,是进程间通信的一种方式。FIFO具有以下特点:

          1.全双工的通信模式,数据先进先出;

          2.可以用于任意的进程之间,通过指定相同的管道文件进行通信;

          3.文件名存在文件系统中,而管道中的内容存在于内存中。可通过open、read、write对其操作;

使用FIFO的步骤如下:

一、创建/打开一个FIFO

FIFO是一种文件类型,在Linux系统中FIFO的类型用p表示。如下所示: 

-rwxr-xr-x 1 root root 7368 2008-10-29 09:05 create_fifo 
        -rw-r--r-- 1 root root 380 2008-10-29 09:05 create_fifo.c 
        prw-r--r-- 1 root root 0 2009-06-12 14:18 myfifo 
        -rwxr-xr-x 1 root root 8178 2008-10-29 08:58 read_fifo 
        -rw-r--r-- 1 root root 1185 2008-10-29 09:00 read_fifo.c 
        -rwxr-xr-x 1 root root 8333 2009-06-12 14:20 write_fifo 
        -rw-r--r-- 1 root root 1139 2009-06-12 14:19 write_fifo.c

可以看到,虽然FIFO文件存在于文件系统中(可供不同的进程打开),但FIFO中的内容都存放在内存中,所以文件大小始终为0。
由于FIFO不是普通文件,所以只能用文件IO来访问。

#include <sys/stat.h> 
        int mkfifo(const char *path, mode_t mode);

函数mkfifo用于创建一个有名管道,参数path指定要创建的FIFO的路径,mode为该管道文件的访问权限,一般用八进制数表示。

#include <sys/stat.h> 
        #include <fcntl.h> 
        int open(const char *path, int oflag, ... );

函数open通过指定路径打开一个文件,不同的进程可以调用open打开同一个FIFO进行通信。参考下面的代码(相关头文件省略)

#define BUF_SIZE 51 
        int main(int argc, char *argv[]) 
        { 
                  int fd;
                  ssize_t n;
                  char buf[BUF_SIZE];
                  if ( argc <2)
                  {
                           fprintf(stdout, “Usage: %s <fifo_path>\n”, argv[0]);
                           exit(1);
                  }
                  if ( mkfifo(argv[1], 0666) < 0 ) // 创建FIFO失败
                  {
                           if (errno != EEXIST ) // 出错原因不是因为管道已存在
                           {
                           fprintf(stderr, “mkfifo() failed %s\n”, strerror(errno));
                           exit(-1);
                           }
                  }
                  if ( (fd = open(argv[1], O_RDWR)) < 0 ) // 打开FIFO出错
                  { // 注:< 优先级要高于 =
                           fprintf(stderr, “open() failed %s\n”, strerror(errno));
                           exit(-1);
                  }
                   …
                   return 0;
        }

二、读/写FIFO

进程打开FIFO后,就可以根据open时指定的选项对其进行相应的读/写操作(请参考open的帮助文档中关于选项的说明)。

#include <unistd.h>
        ssize_t read(int fildes, void *buf, size_t nbyte);
        ssize_t write(int fildes, const void *buf, size_t nbyte);
        ……
        if ((n = read(fd, buf, BUF_SIZE)) < 0 )
        {
                    fprintf(stderr, “read() failed %s\n”, strerror(errno));
                    exit(-1);
        }
        else if ( n = = 0 )
        {
                    fprintf(stdout, “all write sides are closed…\n”);
                    exit(-1);
        }
        else
        {
                    fprintf(stdout, “read %d bytes from FIFO : %s\n”, n, buf);
        }
        ……

对FIFO的写操作,大家可以仿照上面的代码。

最后总结一下在使用FIFO时要注意的问题:

        1. 在用open打开FIFO时有可能会阻塞,原因就是当前只有读端或写端存在。换句话说,如果程序在打开FIFO时指定了只读方式/只写方式,那么该进

程对于打开的FIFO来说就是一个读端/写端。如果指定的是读写方式,那么进程既是读端又是写端。

        2. 从FIFO中读数据时(用read函数),如果没有数据,默认是阻塞等待,直到有数据被写入FIFO。如果read函数返回0,说明该FIFO所有的写端都已关

闭,程序要做相应的处理。

            向FIFO写入数据时(使用write函数),如果FIFO有足够空间,write函数会返回写入的字节数;如果空间不够,write函数会阻塞,直到写完为止。当所

有的读端都关闭时,再向FIFO写数据会出错。内核会向写进程发管道断裂的信号(SIGPIPE), 从而终止该进程。处理的办法有两种:程序以读写方式打开

FIFO或是在程序中捕捉SIGPIPE信号,由用户自行处理。

 

原创粉丝点击