一 管道通信
管道的通信是单向的,先进先出,将一个进程的输出和另一个进程的输入连接在一起
一个进程(写进程)在管道的尾部写数据,另一个进程(读进程)在管道的头部读数据
数据被一个进程从管道里读出后将被从管道删除,读它进程将不能再读它
进程试图读管道时,进程将被阻塞 同样管道已满时,进程在试图向管道写数据,进程将被阻塞
二 无名管道VS有名管道
无名管道用于血缘进程之间的通信
有名管道可以用于任意两个进程
三 无名管道的创建
!!!!!!必须在系统调用fork()之前调用pipe(),否则子进程将不会继承文件描述符
int pipe(int filedis[2]);
当一个管道创建时会建立两个文件描述符 filedis[0] 用于读 filedis[1]用于写
/*****************************************************
> File name: pipe.c
> Author: Mr.YUAN
> 日期: 2017-12-08 09:47
*****************************************************/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
int main()
{
int ret;
pid_t pid;
int fd[2] = {0};
int count = 0;
ret = pipe(fd);
if(-1 == ret)
{
perror("pipe");
exit(1);
}
pid = fork();
if(-1 == pid)
{
perror("fork");
exit(1);
}
else if(0 == pid)
{
sleep(1);
count++;
printf("child process: count = %d\n",count);
ret = write(fd[1],&count,sizeof(int));
if(ret == -1)
{
perror("write");
exit(1);
}
}
else
{
ret = read(fd[0],&count,sizeof(int));
if(ret == -1)
{
perror("read");
exit(1);
}
count++;
printf("parent process :count = %d\n",count);
waitpid(pid,NULL,0);
}
return 0;
}
四 有名管道的创建FIFO
/*****************************************************
> File name: fifo_write.c
> Author: Mr.YUAN
> 日期: 2017-12-08 10:31
*****************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int ret;
int fd;
char buf[100] = {0};
fd = open("fifo.tmp",O_WRONLY | O_EXCL);
if(-1 == fd)
{
perror("open");
exit(1);
}
while(1)
{
scanf("%s",buf);
ret = write(fd,buf,strlen(buf));
if(-1 == ret)
{
perror("write");
exit(1);
}
if(!strncmp(buf,"end",3))
break;
memset(buf,0,sizeof(buf));
}
close(fd);
return 0;
}
/*****************************************************
> File name: fifo_read.c
> Author: Mr.YUAN
> 日期: 2017-12-08 10:20
*****************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int ret ;
int fd;
char buf[100] = {0};
ret = mkfifo("fifo.tmp",O_CREAT | O_EXCL);
if(-1 == ret)
{
perror("mkfifo");
exit(1);
}
fd = open("fifo.tmp",O_RDONLY | O_EXCL);
if(-1 == fd)
{
perror("open");
exit(1);
}
while(1)
{
ret = read(fd,buf,sizeof(buf));
if(-1 == ret)
{
perror("read");
exit(1);
}
if(!strncmp(buf,"end",3))
{
break;
}
printf("read from fifo: %s",buf);
memset(buf,0,sizeof(buf));
}
close(fd);
unlink("fifo.tmp");
return 0;
}