赞
踩
自学笔记,没有历史知识铺垫(省略百度部分)C语言笔记-21-Linux基础-通信管道
pipe()
创建匿名管道 read()
如果管道中没有内容,阻塞write()
如果管道满,阻塞pipe匿名管道示例
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char *msg = "main msg !!\n"; char buf[128]; int fds[2]; int pp = pipe(fds); if (pp == -1) { perror("open pipe failed\n"); return -1; } pid_t p = fork(); if (p == -1) { perror("open child failed\n"); return -1; } if (p == 0) { printf("start child process\n"); close(fds[1]); // 如果管道内没有内容,进程回阻塞在此处 int r = read(fds[0], buf, 128); write(1, buf, r); close(fds[0]); } else { printf("this is main process\n"); close(fds[0]); // wait(NULL); wait在此处时,管道write无法触发,导致子进程管道读取阻塞无法结束,进而导致整个程序阻塞 write(fds[1], msg, strlen(msg)); close(fds[1]); } return 0; } // 执行结果 this is main process main msg !! start child process
mkfifo()
创建命名管道,创建后可使用open
,write
,read
等底层io方式向有名管道文件读写数据,实现多进程通信的效果。命名管道示例
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main(int argc, char *argv[]) { char *msg = "main msg22 !!\n"; char buf[128]; int fifoWritePipe; // 后续打开使用命名管道 if (!access("tempFifo", F_OK)) { // 写入端打开管道 fifoWritePipe = open("tempFifo", O_RDWR); if (fifoWritePipe == -1) { perror("open mkfifo failed\n"); return -1; } } else { // 首次创建管道 fifoWritePipe = mkfifo("tempFifo", 0644); if (fifoWritePipe == -1) { perror("create mkfifo failed\n"); return -1; } } pid_t p = fork(); if (p == -1) { perror("open child failed\n"); return -1; } if (p == 0) { printf("start child process\n"); // 读取端打开管道 int fifoReadPipe = open("tempFifo", O_RDONLY); if (fifoReadPipe == -1) { perror("open mkfifo failed\n"); return -1; } // 子进程读取管道内容 int r = read(fifoReadPipe, buf, 128); write(1, buf, r); close(fifoReadPipe); } else { printf("this is main process\n"); // 主进程写入管道内容 write(fifoWritePipe, msg, strlen(msg)); close(fifoWritePipe); } return 0; } // 执行结果 this is main process main msg22 !! start child process
本章主要为C语言笔记-21-Linux基础-通信管道
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。