(一)发行版:Ubuntu16.04.7
(二)记录:
(1)管道通信分类:
有名管道,无名管道。
(2)无名管道:
只可用于有关系的进程,比如父子进程。
(3)pipe函数:
头文件:<unistd.h>
函数原型:int pipe(int pipefd[2]);
作用:创建管道
pipefd[0]读端
pipefd[1]写端
管道创建需要在创建进程之前。保证父子进程是在同一个管道。
(4)创建无名管道编译运行:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(void)
{
pid_t pid;
int fd[2];
//创建管道
pipe(fd);
printf("fd[0] is %d\n",fd[0]);
printf("fd[1] is %d\n",fd[1]);
pid=fork();
if(pid<0)
printf("error.\n");
//父进程
if(pid>0){
}
//子进程
if(pid==0){
}
}
之所以是3和4是因为,0、1、2是标准输入、输出、出错
fd[0]读,fd[1]写
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int fd[2];
char buf[32]={0};
//创建管道
pipe(fd);
printf("fd[0] is %d\n",fd[0]);
printf("fd[1] is %d\n",fd[1]);
pid=fork();
if(pid<0)
printf("error.\n");
//父进程
if(pid>0){
int status;
close(fd[0]);
write(fd[1],"hello",5);
close(fd[1]);
wait(&status);
exit(0);
}
//子进程
if(pid==0){
close(fd[1]);
read(fd[0],buf,32);
printf("buf is %s\n",buf);
close(fd[0]);
exit(0);
}
}
(5)有名管道:
可以做到两个没有关系的进程之间的通信。通过创建一个fifo文件,不需要在进程创建前创建有名管道,这是与无名管道不同的。
(6)mkfifo函数:
(7)命令创建有名管道:
可以发现管道是不占空间的
(8)mkfifo函数创建有名管道:
ymgd_write.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
int ret;
int fd;
if(argc<2){
printf("Usage:%s<fifo name>\n",argv[0]);
return -1;
}
//access判断管道文件是否存在,不存在则创建
if(access(argv[1],F_OK)==-1){
ret =mkfifo(argv[1],0666);
if(ret == -1)
{
printf("mkfifo is error\n");
return -2;
}
printf("mkfifo is ok\n");
}
fd =open(argv[1],O_WRONLY);
while(1){
sleep(1);
write(fd,"hello",5);
}
close(fd);
return 0;
}
ymgd_read.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char *argv[])
{
int ret;
int fd;
char buf[32]={0};
if(argc<2){
printf("Usage:%s<fifo name>\n",argv[0]);
return -1;
}
fd =open(argv[1],O_RDONLY);
while(1){
sleep(1);
read(fd,buf,32);
printf("buf is %s\n",buf);
memset(buf,0,sizeof(buf));
}
close(fd);
return 0;
}
运行效果
通信是通过fifo这个文件进行的,实现没有亲缘关系的通信。
(三)命令: