Chinaunix首页 | 论坛 | 博客
  • 博客访问: 279519
  • 博文数量: 109
  • 博客积分: 2116
  • 博客等级: 大尉
  • 技术积分: 1062
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-22 15:38
文章分类

全部博文(109)

文章存档

2013年(2)

2011年(16)

2010年(90)

2009年(1)

我的朋友

分类: LINUX

2010-07-09 11:29:11

今天完成命名管道的实验。

命名管道也是按照文件操作流程进行的,可以看做特殊文件。

写管道进程:打开--关闭

读管道进程:打开--关闭

本实验采用阻塞式读写管道,一个程序写,另一个读。

源代码来自华清远见:

写:

#include

#include

#include

#include

#include

#include

#include

 

#define MYFIFO  "/tmp/myfifo"

#define MAX_BUFFER_SIZE     PIPE_BUF

 

int main(int argc, char* argv[])

{

    char buff[MAX_BUFFER_SIZE];

    int fd;

    int nwrite;

 

    if(argc <= 1)

    {

        printf("usage: ./write string!\n");

        exit(1);

    }

    sscanf(argv[1], "%s", buff);

 

    fd = open(MYFIFO, O_WRONLY);//打开管道,写阻塞方式

    if(fd == -1)

    {

        printf("open fifo file error!\n");

        exit(1);

    }

    if((nwrite = write(fd, buff, MAX_BUFFER_SIZE)) > 0)//写管道

    {

        printf("write '%s' to FIFO!\n ", buff);

    }

    close(fd);//关闭

    exit(0);

}

 

读:

#include

#include

#include

#include

#include

#include

#include

 

#define MYFIFO  "/tmp/myfifo"

#define MAX_BUFFER_SIZE     PIPE_BUF

 

int main()

{

    char buff[MAX_BUFFER_SIZE];

    int fd;

    int nread;

       //判断管道是否存在,如果不存在则创建

    if(access(MYFIFO, F_OK) == -1)

    {

        if((mkfifo(MYFIFO, 0666) < 0) && (errno != EEXIST))

        {

            printf("cannot creat fifo file!\n");

            exit(1);

        }

    }

 

    fd = open(MYFIFO, O_RDONLY);//打开管道,只读阻塞方式

    if(fd == -1)

    {

        printf("open fifo file error!\n");

        exit(1);

    }

 

    while(1)

    {

        memset(buff, 0, sizeof(buff));

        if((nread = read(fd, buff, MAX_BUFFER_SIZE)) > 0)//读管道

        {

            printf("read '%s' from FIFO\n", buff);

        }

    }

    close(fd);//关闭

    exit(0);

}

 

编译运行,打开两个终端,一个写,一个读。结果如下:

阅读(458) | 评论(0) | 转发(0) |
0

上一篇:守护进程实验

下一篇:消息队列

给主人留下些什么吧!~~