文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>进程通信----fifo

进程通信----fifo

时间:2010-08-25  来源:huazaicola

进程通信----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;
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载