命名管道理解与简单C实现

来源:互联网 发布:统计师的python日记 编辑:程序博客网 时间:2024/06/08 19:51

命名管道主要解决进程间消息传递的问题。 虽然是以文件的形式, 但是实际上消息仍然是存储在内存中的, 这也是无论何时查看管道文件都是0kb的原因。

以下是两个实例fifo_write.c和fifo_read.c:

fifo_read.c:

#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <limits.h>#include <string.h>#include <unistd.h>#define MYFIFO   "myfifo"    /* 有名管道文件名*/#define MAX_BUFFER_SIZE   PIPE_BUF/*常量PIPE_BUF 定义在于limits.h中*/char buff[MAX_BUFFER_SIZE];int  fd;int  nread;void f_read(){    fd = open(MYFIFO, O_RDONLY);    memset(buff, 0, sizeof(buff));    nread = read(fd, buff, MAX_BUFFER_SIZE);    printf("read:'%s' length:%d\n", buff, nread);    close(fd);}int main(){    if (access(MYFIFO, F_OK) == -1){        if ((mkfifo(MYFIFO, 0666) < 0) && (errno != EEXIST)){             printf("Cannot create fifo file\n");                 exit(1);        }    }    while (1){        f_read();    }     exit(0);}
fifo_write.c:

#include<sys/types.h>#include<sys/stat.h>#include<errno.h>#include<fcntl.h>#include<stdio.h>#include<stdlib.h>#include<limits.h>#include<unistd.h>#include<string.h>#define MYFIFO "myfifo"#define MAX_BUFFER_SIZE PIPE_BUFint fd;char buff[MAX_BUFFER_SIZE];int nwrite;void f_write(){    fd = open(MYFIFO, O_WRONLY);    write(fd, buff, MAX_BUFFER_SIZE);    close(fd);}int main(int argc, char * argv[]){    if (access(MYFIFO, F_OK) == -1){        if ((mkfifo(MYFIFO, 0666) < 0) && (errno != EEXIST)){             printf("Cannot create fifo file\n");                 exit(1);        }      }    while(gets(buff)!=EOF){        f_write();    }exit(0);}
Centos 7下编译:

gcc -o fifo_write fifo_write.c

gcc -o fifo_read fifo_read.c

运行程序:

在fifo_write下输出传输的文本, fifo_read下会读出对应的信息。

另外此种消息传递是阻塞式的, 先打开fifo_read或fifo_write都是一样的, 程序都会正常运行。

其它的相关管道的知识, 可以查阅相关的资料。  但是关于管道的使用, 容易出现问题, 项目中一旦出现阻塞不容易处理, 所以最终自己还是放弃了用管道来进行数据的传输。

原创粉丝点击