Chinaunix首页 | 论坛 | 博客
  • 博客访问: 642012
  • 博文数量: 128
  • 博客积分: 4385
  • 博客等级: 上校
  • 技术积分: 1546
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-22 14:05
文章分类

全部博文(128)

文章存档

2012年(2)

2011年(51)

2010年(75)

分类: LINUX

2010-08-25 10:26:17

进程通信----fifo
   pipe只能用父子经常之间的通信,而fifo适合任何进程之间。
流程:
1.创建fifo,以非阻塞方式打开。
说明:A:在阻塞方式下打开,(没有指定O_NONBLOCK)
(1)当以只读open是,进程阻塞,直到有进程为写而打开;
(2)当以只写open打开时,进程阻塞,直到有进程为读而打开。
   B: 若指定O_NONBLOCK 方式打开
(1)若只读open 将立即返回,若只写open将出错!  所以先创建读进程,后创建写进程。
(即:在创建fifo进程,执行读,其他进程直接打开fifo后,执行写)
2.读操作
3.删除fifo文件
 
例: 在当前文件下创建fifo文件 
fifo_read.c

#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 "/tmp/myfifo"

main(void)
{
    int fd;
    int read_size;
    char buf[20];
    if((mkfifo("./myfifo", O_CREAT|O_EXCL) < 0) && (errno != EEXIST)) // !!

    {
        printf("fifo creat error\n");
        exit(1);
    }
    printf("open and reading...\n");
    if((fd = open("./myfifo", O_RDONLY|O_NONBLOCK,0)) < 0) //creat and open in O_NONBLOCK

    {
        printf("open fifo:%s\n", strerror(errno));
        exit(1);
    }
    printf("opened, reading ..\n");
    while(1)
    {
        memset(buf, 0, sizeof(buf));  // 数组要初始化
        if((read_size = read(fd, buf, sizeof(buf))) < 0) //use right number of () 此处一定注意!容易出错!适当的加括号

        {    
            printf("read error:%s\n", strerror(errno));
            exit(1);
        }
        printf("read %s from fifo:%d\n", buf,read_size); // add '\n' in printf, or error 

        sleep(1);        //sleep, execute slowly!

    }
    pause();
    unlink("./myfifo");
}

程序两个容易犯错的地方:

1.  if((read_size = read(fd, buf, sizeof(buf))) < 0) //use right number of () 

此处一定注意!容易出错!适当的加括号


2.printf("read %s from fifo:%d\n", buf,read_size); // add '\n' in printf, or error 

此处注意‘\n’别丢了

fifo_write.c


 

#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 "/tmp/myfifo"

int main(int argc, char *argv[])
{
    int fd;
    char w_buf[20];
    int write_size;
    if((fd=open("./myfifo",O_WRONLY | O_NONBLOCK, 0)) < 0)
    {
        printf("open error:%s\n", strerror(errno));
        exit(1);
    }
    printf("open ok\n");
    strcpy(w_buf, argv[1]);
    if((write_size = write(fd, w_buf, sizeof(w_buf))) < 0)
    {
        printf("write error:%s\n", strerror(errno));
        exit(1);
    }
    printf("write %s to fifo\n", w_buf);
    close(fd);
    return 0;
}


阅读(1066) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-08-27 08:46:29

Download More than 1000 free IT eBooks: http://free-ebooks.appspot.com