进程间通信
管道:管道是一种半双工的通信方式,数据只能单向流动。
有名管道:可用在同意主机下的任意间的进程通信 — FIFO
无名管道:只能用在具有亲缘关系的进程中通信(同一主机)— PIPE
管道的特点:
1、读阻塞:当读端和写端都存在时,管道中无数据时,read读阻塞
2、read到0:当所有写端关闭时,管道中有数据则读数据,无数据则read不阻塞返回0
3、写阻塞:当读端和写端都存在时,当管道满,则发生写阻塞(管道最大64k)
4、当所有读端都关闭时,向管道中写数据,发生管道破裂(异常)
无名管道
#include <fcntl.h> /* Obtain O_* constant definitions */
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main(void)
{
int pipefd[2] = {0};
int ret = pipe(pipefd);
if(ret < 0)
{
perror("fail pipe");
}
pid_t pid = fork();
if(pid > 0)
{
close(pipefd[0]);
while(1)
{
char buff[1024] = {0};
scanf("%s",buff);
getchar();
//buff[strlen(buff)-1] = '\0';
write(pipefd[1],buff,strlen(buff));
if(0 == strcmp(buff,".quit"))
{
break;
}
}
wait(NULL);
}else if(0 == pid)
{
close(pipefd[1]);
while(1)
{
char buff[1024] = {0};
read(pipefd[0],buff,sizeof(buff));
if(0 == strcmp(buff,".quit"))
{
break;
}
printf("%s\n",buff);
}
}else
{
perror("fail fork");
}
close(pipefd[0]);
close(pipefd[1]);
return 0;
}
有名管道
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include<string.h>
int main(void)
{
int fifo = mkfifo("./mkfifo",0664);
if(fifo < 0 && errno != EEXIST)
{
perror("fail mkfifo");
return -1;
}
int fd = open("./mkfifo",O_RDONLY);
if(fd < 0)
{
perror("fail open");
return -1;
}
while(1)
{
char buff[1024] = {0};
read(fd,buff,sizeof(buff));
if(strcmp(buff,".quit") == 0)
{
break;
}
printf("%s\n",buff);
}
close(fd);
remove("./mkfifo");
return 0;
}
----------------------------------------------------------------------------------------
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include<string.h>
int main(void)
{
int fifo = mkfifo("./mkfifo",0664);
if(fifo < 0 && errno != EEXIST)
{
perror("fail mkfifo");
return -1;
}
int fd = open("./mkfifo",O_WRONLY);
if(fd < 0)
{
perror("fail open");
return -1;
}
while(1)
{
char buff[1024] = {0};
scanf("%s",buff);
getchar();
write(fd,buff,strlen(buff));
if(strcmp(buff,".quit") == 0)
{
break;
}
}
close(fd);
return 0;
}