无名管道 pipe
只能用于具备亲缘关系的进程间通信,容量大小64K,管道文件大小为0,只起到标识作用,写入管道的数据存在内存上,不能使用lseek,半双工(同一时间内只能一端发另一端收),头文件<unistd.h>
读:有多少读多少,若没有数据,阻塞等待
写:有多少写多少,直到写满64K
写端关闭,有多少读多少,若没有数据,立即返回
读端关闭,管道破裂,系统发送SIGPIPE信号杀死本进程
创建无名管道
int pipe(int pipefd[2])
pipefd:自己定义的数组,pipefd[0]变成读端,pipefd[1]变成写端
返回值:成功 = 0,失败 = -1并置位errno错误码
示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char const *argv[])
{
int pipefd[2];
char buf[1024] = {0};
pid_t pid;
//1.创建管道
if(pipe(pipefd) == -1){
perror("pipe create error");
return -1;
}
//2.创建进程
pid = fork();
if(pid == -1){
perror("fork error");
return -1;
}else if(pid == 0 ){
close(pipefd[0]); //关闭读取端
//1.子进程
while(1){
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
write(pipefd[1],buf,strlen(buf));
if(strncmp(buf,"quit",4)==0)
break;
}
printf("子进程退出了\n");
cl