目录
二、文件输入重定向
三、管道
四、信号
三、管道
管道分为:无名管道和有名管道。
1、无名管道
使用pipe(2)可创建无名管道
#include<unistd.h>
int pipe(int pipefd[2]);
功能:
创建可用于进程间通信的单向管道
参数:
pipefd[2]:
pipefd[0]:读端
pipefd[1]:写端
返回值:
成功:0
错误:-1,errno被设置
思路:
(1)父进程创建管道
(2)fork(2)创建子进程
(3)父进程关闭写端、子进程关闭读端
(4)子进程写,父进程读
注意:
无名管道中需要使用到文件描述符,所以,无名管道应用于具有亲缘关系(父子,兄弟)的进程通信
#include<stdio.h> #inlcude<unistd.h> #include<sys/typs.h> #include<sys/wait.h> #include<string.h> #include<stdlib.h> int main(void){ pid_t pid; char msg[]="this is a test"; char buf[128]; int fd[2]; //创建子进程 pid=fork(); //创建管道 int r =pipe(fd); if(r==-1){ perror("pipe"); return 2; } if(pid==-1){ perror("fork"); return 1; } if(pid==0){ close(fd[0]);//关闭读端 write(fd[1],msg,strlen(msg));//写入管道 exit(0); }else{ close(fd[1]); int rt=read(fd[0],buf,128); write(1,buf,rt); wait(NULL); } return 0; }
2、有名管道
有名管道的实质是创建一个管道问价你,一个向文件写数据,一个向文件读数据。
创建有名管道可以使用函数mkfifo(3)
#include<sys/types.h>
#include<sys/stat.h>
int mkfifo(const char *pathname,mode_t mode);
功能:
创建一个特殊的FIFO文件,文件名字为pathname,mode指定了文件的权限(mask&~umask)
参数:
pathname:管道文件的名字
mode:管道文件的权限
返回值:
成功:0
失败:-1,errno被设置
有名管道通信,下面为进程A的代码
#include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<string.h> #include<fcntl.h> #include<unistd.h> int main(int argc,char *argv){ char *msg[]="hello world "; //创建管道文件 int m=mkfifo(argv[1],0664); if(m==-1){ perror("mkfifo"); return 1; } //打开管道文件 int fd=open(argv[1],O_RDWR); if(fd==-1){ perror("open"); return 2; } write(fd,msg,strlen(msg)+1 ); close(fd); return 0; }
下面为进程B的代码
#include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<string.h> #include<fcntl.h> #include<unistd.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; }