进程间通信编程(3) - 有名管道

使用管道只能在相关的程序之间传递数据,即这些程序是由一个共同的祖先进程启动的。如何在不相关的进程之间交换数据呢?
可以用FIFO文件完成这项工作,它通常被称为命名管道(named pipe)。命名管道是一种特殊类型的文件,它在文件系统中以文件名的形式存在,但它的行为却和没有名字的管道类似。
可以在命名行上创建命名管道,也可以在程序中创建。命令行的命令是:
mkfifo filename

# include <sys/types.h>
# include <sys/stat.h>
int mkfifo(const char * pathname, mode_t mode)
pathname:FIFO文件名
mode:属性(见文件操作章节)
一旦创建了一个FIFO,就可用open打开它,一般的文件访问函数(close、read、write等)都可用于FIFO
/*****************************************************
Funcion List:    fifo_read
*****************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

#define FIFO_SERVER "/tmp/fifoserver"

int main()
{
    int fd;
    char r_buf[1000];
    int r_num;
    int ret;

    memset(r_buf,0,sizeof(r_buf));

    fd = open(FIFO_SERVER,O_RDONLY);

    if (fd == -1)
    {
        perror("open fifo error!\n");
        exit(-1);
    }

    while (1)
    {
        sleep(2);
        memset(r_buf,0,sizeof(r_buf));
        r_num = read(fd,r_buf,1000);

        if (r_num == -1 && errno != EINTR)
        {
            perror("read error!\n");
            exit(-1);
        }
        r_buf[r_num] = '\0';
        printf("real read bytes :%d , is %s\n",r_num,r_buf);
    }

    unlink(FIFO_SERVER);

    return 0;
}

/*****************************************************
Funcion List:    fifo_write
*****************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

#define FIFO_SERVER "/tmp/fifoserver"

int main()
{
    int fd,ret;
    char w_buf[1000];
    int  w_num;

    memset(w_buf,0,sizeof(w_buf));

    ret = mkfifo(FIFO_SERVER,O_CREAT|O_EXCL);

    if(ret < 0 && errno != EEXIST)
    {
        perror("create fifo error !");
        exit(-1);
    }

    fd = open(FIFO_SERVER,O_WRONLY);

    if(fd == -1)
    {
        perror("open file error!\n");
        exit(-1);
    }

    scanf("%s",w_buf);

    w_num = write(fd,w_buf,strlen(w_buf));

    if(w_num == -1 && errno != EINTR)
    {
        perror("write error !");
        exit(-1);
    }
    else if(w_num > 0)
    {
        printf("real write num is %d\n",w_num);
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值