六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 55|回复: 0

命名管道实现样例

[复制链接]

升级  46%

33

主题

33

主题

33

主题

秀才

Rank: 2

积分
119
 楼主| 发表于 2013-1-27 04:44:28 | 显示全部楼层 |阅读模式
[root@liumengli name_pipe]# mknod my_pipe p (创建命名管道,也可以通过系统调用来安装)
[root@liumengli name_pipe]# cat name_pipe_read.c
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "errno.h"
#include "fcntl.h"

int main() {
        char buf[20];
        int pipe_read;
        int n_read;


        pipe_read = open("./my_pipe", O_RDONLY, 0);
       //打开管道,只读方式,注意与下面的区别,读者可以自己试试,可能参数有错,自己可以找到
        //pipe_read = open("./my_pipe", O_RDONLY|O_NONBLOCK, 0);

        if(pipe_read == -1) {
                printf("error\n");
                return 1;
        }

        memset(buf, 0, sizeof(buf));
        n_read = read(pipe_read, buf, 20);
        printf("You read %d chars\n", n_read);
        printf("%s\n", buf);
        return 0;
}
//读管道程序
[root@liumengli name_pipe]# cat name_pipe_read.c
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "errno.h"
#include "fcntl.h"

int main() {
        char buf[20];
        int pipe_read;
        int n_read;


        pipe_read = open("./my_pipe", O_RDONLY, 0);

        if(pipe_read == -1) {
                printf("error\n");
                return 1;
        }

        memset(buf, 0, sizeof(buf));
        n_read = read(pipe_read, buf, 20);
        printf("You read %d chars\n", n_read);
        printf("%s\n", buf);
        return 0;
}
//写管道程序,2个进程通过my_pipe命名管道通信,如果对命名管道有兴趣,可以留言.
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表