首页服务器Linux服务器 Linux命名管道的使用

Linux命名管道的使用

Linux命名管道非常适合同一机器上两个进程之间传递数据,其形式也是一个文件,但是读取与写入时遵循FIFO的原则。在使用命名管道时有两种方式进行读/写:阻塞与非阻塞。

使用命名…

Linux命名管道非常适合同一机器上两个进程之间传递数据,其形式也是一个文件,但是读取与写入时遵循FIFO的原则。在使用命名管道时有两种方式进行读/写:阻塞与非阻塞。

使用命名管道很容易写出生产者与消费者的程序。下面这个程序摘自《Linux程序设计(第3版)》

producer.c

#include
#include
#include
#include
#include
#include
#include
#include

#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF
#define TEN_MEG (1024 * 1024 * 10)

int main()
{
int pipe_fd;
int res;
int open_mode = O_WRONLY;
int bytes_sent = 0;
char buffer[BUFFER_SIZE + 1];

if(access(FIFO_NAME,F_OK) == -1){
res = mkfifo(FIFO_NAME,0777);
if(res != 0){
fprintf(stderr,"Could not create fifo %s/n",FIFO_NAME);
exit(EXIT_FAILURE);
}
}

printf("Process %d opening FIFO O_WRONLY/n",getpid());
pipe_fd = open(FIFO_NAME,open_mode);
printf("Process %d result %d/n",getpid(),pipe_fd);

if(pipe_fd != -1){
while(bytes_sent < TEN_MEG){
res = write(pipe_fd,buffer,BUFFER_SIZE);
if(res == -1){
fprintf(stderr,"Write error on pipe/n");
exit(EXIT_FAILURE);
}
bytes_sent += res;
}
(void)close(pipe_fd);
}
else{
exit(EXIT_FAILURE);
}

printf("Process %d finished/n",getpid());
exit(EXIT_SUCCESS);
}


customer.c

#include
#include
#include
#include
#include
#include
#include
#include

#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF

int main()
{
int pipe_fd;
int res;

int open_mode = O_RDONLY;
char buffer[BUFFER_SIZE + 1];
int bytes_read = 0;

memset(buffer,'/0',sizeof(buffer));

printf("Process %d opening FIFO O_RDONLY/n",getpid());
pipe_fd = open(FIFO_NAME,open_mode);
printf("Process %d result %d/n",getpid(),pipe_fd);

if(pipe_fd != -1){
do{
res = read(pipe_fd,buffer,BUFFER_SIZE);
bytes_read += res;
}while(res > 0);
(void)close(pipe_fd);
}
else{
exit(EXIT_FAILURE);
}

printf("Process %d finished, %d bytes read/n",getpid(),bytes_read);
exit(EXIT_SUCCESS);
}

本文来自网络,不代表1号站长-站长学院|资讯交流平台立场。转载请注明出处: https://www.1cn.cc/fwq/Linux/8107.html
上一篇Linux:Ubuntu 11.04下安装极点五笔输入法
下一篇 Linux下有趣的命令
admin

作者: admin

这里可以再内容模板定义一些文字和说明,也可以调用对应作者的简介!或者做一些网站的描述之类的文字或者HTML!

为您推荐

评论列表()

    联系我们

    联系我们

    0898-88888888

    在线咨询: QQ交谈

    邮箱: email@wangzhan.com

    工作时间:周一至周五,9:00-17:30,节假日休息

    关注微信
    微信扫一扫关注我们

    微信扫一扫关注我们

    关注微博
    返回顶部