【C语言】【unix c】如何创建有名管道

来源:互联网 发布:淘宝流量充值怎么开店 编辑:程序博客网 时间:2024/06/06 02:27
有名管道其实是一个文件,这个文件只能用于两个进程间通信的桥梁,不存储任何数据内容    如何创建有名管道 :        mkfifo(3)            #include <sys/types.h>            #include <sys/stat.h>            int mkfifo(const char *pathname, mode_t mode);            功能:创建一个有名管道的文件            参数:                pathname:指定了有名管道的名字                mode:指定了管道文件的权限            返回值:成功 0                错误 -1            举例:有名管道文件的创建(mkfifo.c)文件名由命令行传入,权限0664            创建管道文件: #include <stdio.h>                    #include <sys/types.h>                    #include <sys/stat.h>                    int main(int argc, char *argv[]) {                        int m = mkfifo(argv[1],0664);                        if(m == -1) {                        perror("mkfifo");                        return -1;                        }                        return 0;                    }            测试:                编写代码向有名管道写数据(PA.c)                    #include <stdio.h>                    #include <p_file.h>                    #include <string.h>                    int main(int argc, char *argv[]) {                        char *msg = "this is a test!\n";                        int fd =open(argv[1], O_WRONLY);                        if(fd == -1) {                        perror("open");                        return -1;                        }                        write(fd, msg, strlen(msg));                        close(fd);                        return 0;                    }                编写代码从有名管道读取数据(PB.c)                    #include <stdio.h>                    #include <p_file.h>                    #include <string.h>                    int main(int argc, char *argv[]) {                        char buf[128];                        int fd =open(argv[1], O_RDONLY);                        if(fd == -1) {                        perror("open");                        return -1;                        }                        int r = read(fd, buf, 128);                        write(1, buf, r);                        close(fd);                        return 0;                    }                运行:                PA:                    tarena@ubuntu:~/day/day32$ A hello                    -                PB:                     tarena@ubuntu:~/day/day32$ B hello        先运行PA后运行PB的结果:this is a test!
原创粉丝点击