#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<string.h>#define MSG "HELLO"intmain(){int fd[2];
pid_t pid;// 先创建管道,避免子进程重复创建管道pipe(fd);
pid =fork();if(pid >0){printf("Parent:%d process running...\n",getpid());close(fd[0]);write(fd[1], MSG,strlen(MSG));close(fd[1]);while(1);}elseif(pid ==0){printf("Child:%d process running...\n",getpid());char buf[1024];int len;bzero(buf,sizeof(buf));close(fd[1]);
len =read(fd[0], buf,sizeof(buf));close(fd[0]);exit(0);}else{perror("fork call error");exit(0);}return0;}
1.10 匿名管道使用时的几种特殊情况
1.读端开启,写端关闭:读端读完管道内数据后,再次读返回0(相当于读到文件末尾);
2.写端开启,读端关闭:尝试向管道内写数据,内核向进程发送 sigpipe 信号,导致写端终止;
3.读写端开启,写端没有进行写数据操作:读端读完管道内数据后,再次读时阻塞;
4.读写端开启,读端没有读数据:写端写满管道后,再次写时阻塞;
1.11 管道的优缺点
1.匿名管道单工工作,只支持单向数据流;
2.没有名字,无法分辨;
3.只能用于具有亲缘关系的进程之间;
4.管道的缓冲区有限,管道存在于内存中,在创建管道时为缓冲区分配一个页面大小;
5.管道所传送的是无格式字节流,这就要求管道的读端和写端必须事先约定好数据的格式;
2.有名管道
2.1 创建步骤
1.首先在终端 mkfifo hello ,创建一个有名管道;
2.在分别完成读端和写端;
写端:
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#define MSG "Hello SLAM"intmain(int argc,char** argv){if(argc <2){printf("ERROR! TOO LESS ARGVS,PLS INPUT LIKE:\n");printf("./write NAME\n");exit(0);}int fd =open(argv[1], O_WRONLY);write(fd, MSG,strlen(MSG));close(fd);return0;}
读端
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>intmain(){if(argc <2){printf("ERROR! TOO LESS ARGVS,PLS INPUT LIKE:\n");printf("./read NAME\n");exit(0);}int fd;
fd =open(argv[1], O_RDONLY);char buf[1024];bzero(buf,sizeof(buf));int len =read(fd, buf,sizeof(buf));close(fd);printf("%s is from %s\n", buf, argv[1]);return0;}