管道通信有一个特点:通信是半双工的,即管道的一端只能读或者只能写
管道通信可以分为:匿名管道通信和命名管道通信两种
1. 匿名管道通信:适合用于父子进程间的通信
#include<unistd.h>
#include<stdio.h>
#include<string.h>
/*
匿名管道通信,本机父子进程通信方式
*/
int main()
{
int pipefd[2];
pid_t pid;
char buf[20];
pipe(pipefd); //create pipe!
pid = fork();
if(pid < 0)
printf("fork failed\n");
if(pid > 0)
{
close(pipefd[0]);
const char* s = "hello child";
printf("i am father , i am writting :%s\n",s);
write(pipefd[1],s,strlen(s)+1);
close(pipefd[1]);
}
else
{
close(pipefd[1]);
read(pipefd[0],buf,sizeof(buf));
printf("i am child,i am reading :%s\n",buf);
close(pipefd[0]);
}
waitpid(pid,NULL,0);
return 0;
}
2. 命名管道通信:用于任何两个进程间的通信
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
/**
命名管道
*/
#define FIFO "/home/wyz19891024/code/ccode/fifo"
int main()
{
int ret;
int fd;
//const char* s = "hello bothers!";
char buf[20];
umask(0); //默认文件访问权限022 umask(mode)
ret = mkfifo(FIFO,0666); //文件权限为 0666 & (~0);
if(ret < 0)
{
printf("mkfifo failed\n");
return 1;
}
fd = open(FIFO,O_WRONLY);
while(1)
{
fgets(buf,sizeof(buf),stdin);
write(fd,buf,sizeof(buf));
if(strncmp(buf,"quit",4) == 0)
{
unlink(FIFO);
close(fd);
break;
}
}
return 0;
}
/****-----client------****/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
/**
命名管道
*/
#define FIFO "/home/wyz19891024/code/ccode/fifo"
int main()
{
int fd;
char buf[20];
fd = open(FIFO,O_RDONLY);
while(1)
{
read(fd,buf,sizeof(buf));
printf("get %s\n",buf);
if(strncmp(buf,"quit",4) == 0)
break;
}
close(fd);
return 0;
}