一、匿名管道
匿名管道根据父子进程共享代码,父进程创建一个管道文件,并有两个文件描述符指向管道文件,子进程也有两个文件描述符指向管道文件。利用文件描述符,一端关闭读,一端关闭写,来实现通信。
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
int main()
{
int _pipefd[2] = {0,0};
if(pipe(_pipefd) < 0){
perror("pipe");
return 1;
}
pid_t id = fork();
if(id < 0){
perror("fork");
return 2;
}else if(id == 0){
close(_pipefd[0]);
int i = 0;
const char *msg = "hello bit\n";
int count = 5;
while(count){
msg = "i am child!";
write(_pipefd[1],msg,strlen(msg));
sleep(1);
count--;
}
close(_pipefd[1]);
exit(0);
}else{
close(_pipefd[1]);
char _mesg[100];
int j = 0;
while(j < 100)
{
memset(_mesg,'\0',sizeof(_mesg));
int ret = read(_pipefd[0],_mesg,sizeof(_mesg));
printf("%s:code is:%d\n",_mesg,ret);
j++;
}
if(waitpid(id,NULL,0)<0)
{
return 3;
}
}
return 0;
}
二、命名管道
命名管道可以让两个没有任何关系的进程实现通信
1.创建一个管道文件,进程权限为只读
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
umask(0);
if(mkfifo("./fifo",0666|S_IFIFO)<0){
perror("mkfifo");
return 1;
}
int fd = open("./fifo",O_RDONLY);
if(fd < 0){
perror("open");
return 2;
}
char buf[128];
while(1){
ssize_t s = read(fd,buf,sizeof(buf));
if(s > 0){
buf[s] = "\0";
printf("client#%s\n",buf);
}else if( s==0){
printf("client quit! I quit!\n");
break;
}else{
perror("read");
}
}
close(fd);
return 0;
}
2.让另一个进程也操作这个管道文件,权限为只写
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
int fd = open("./fifo",O_WRONLY);
if(fd < 0){
perror("open");
return 2;
}
char buf[128];
while(1){
printf("please Enter#");
fflush(stdout);
ssize_t s = read(0,buf,sizeof(buf));
if(s > 0){
buf[s-1] = "\0";
write(fd,buf,strlen(buf));
}
}
close(fd);
return 0;
}
三、实现
1.必须先执行创建管道的进程server
2.再执行client写入
3.server看到client写入的内容