一、命名管道通信
管道通信分为:无名管道和有名管道
无名管道是用于父子孙进程,之间有血缘关系
有名管道:用于任意两个进程
无名管道:
1、创建:int pipe(int filedis[2]); 它会创建两个文件描述符 filedis[0] 用于读管道
filedis[1] 用于写管道
(通常先创建一个管道,再通过fork函数创建一个子进程,该子进程会继承父进程所创建的管道。必须在系统调用fork()前调用pipe(),否则子进程将不会继承文件描述符)
2、关闭:close(filedis[0]),close(filedis[1])
//利用无名管道进行进程间通信,父进程write,子进程read
//所需要用到的函数pipe,fork,write,read,memset,strcmp
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
void Write(int fd)
{
char buf[32] = {0};
memset(buf,0,sizeof(buf));
printf("please input what you would write:\n");
fgets(buf,sizeof(buf),stdin);
int ret = write(fd,buf,sizeof(buf));
if(-1 == ret)
{
perror("write");
exit(1);
}
}
void Read(int fd)
{
char buf[32] = {0};
memset(buf,0,sizeof(buf));
int ret = read(fd,buf,sizeof(buf));
if(-1 == ret)
{
perror("read");
exit(1);
}
printf("read from pipe:%s\n",buf);
}
int main()
{
int ret,fd[2] = {0};
pid_t pid;
ret = pipe(fd);//创建一个无名管道
if(-1 == ret)
{
perror("pipe");
exit(1);
}
pid = fork();
if(-1 == pid)
{
perror("fork");
exit(1);
}
else if(0 == pid)//子进程,read
{
close(fd[1]);
Read(fd[0]);
}
else//父进程,write
{
close(fd[0]);
Write(fd[1]);
}
return 0;
}
二、命名管道
fifo_read.c
//应用有名管道进行不同进程之间的通信,其实是在磁盘上打开一个tmp文件进行读写
//所要应用到的函数:mkfifo,open,read,close,unlink,strcmp
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd,ret;
char buf[32];
mkfifo("1.tmp",777);
fd = open("1.tmp",O_RDONLY);
if(-1 == fd)
{
perror("open");
exit(1);
}
while(1)
{
ret = read(fd,buf,sizeof(buf));
if(-1 == ret)
{
perror("read");
exit(1);
}
printf("read from 1.tmp :%s\n",buf);
if(!strcmp(buf,"bye\n"))
{
break;
}
memset(buf,0,sizeof(buf));
}
close(fd);
unlink("1.tmp");
return 0;
}
fifo_write.c
//有名管道写进程
//open,write,strcmp,close
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int fd,ret;
char buf[32] = {0};
fd = open("1.tmp",O_WRONLY);
if(-1 == fd)
{
perror("open");
exit(1);
}
while(1)
{
printf("please input what you would to write :\n");
fgets(buf,sizeof(buf),stdin);
ret = write(fd,buf,strlen(buf));
if(-1 == ret)
{
perror("write");
exit(1);
}
if(!strcmp(buf,"bye\n"))
{
break;
}
memset(buf,0,sizeof(buf));
}
close(fd);
return 0;
}