与无名管道不同,有名管道可以在进程为非血缘关系的情况下实现双向的通信,无名管道只能进行父对子之间的通信。
顾名思义,有名管道首先要创建管道,这里我们使用创建管道的函数是myfifo:
// An highlighted block
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int ret;
ret=mkfifo("./mkfifo",0777);
if(ret<0)
{
printf("creat mkfifo failure \n");
return -1;
}
printf("creat myfifo sucess \n");
return 0;
}
P为有名管道的描述符,rwxrwxr-x为该文件权限,我们在程序中创建了文件,并设置其权限为777,去发现创建后的文件权限与我们设置的权限不同,这是因为在文件、目录等创建的时候会和0002相与,一般可以通过命令查看该数字。
有名管道建立好以后下面给出两个互不相干的进程。
// An highlighted block
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
int fd;
int i;
char process_inter=0;
fd=open("./mkfifo",O_WRONLY);
if(fd<0)
{
printf("open myfifo failure\n");
return -1;
}
printf("open myfifo sucess\n");
for(i=0;i<5;i++)
{
printf("this is first process i=%d\n",i);
usleep(100);//将进程挂起100us
}
process_inter=1;
sleep(5);
write(fd,&process_inter,1);
while(1);
return 0;
}
// An highlighted block
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
int fd;
int i;
int process_inter=0;
fd=open("./mkfifo",O_RDONLY);
if(fd<0)
{
printf("open myfifo failre\n");
return -1;
}
printf("open myfifo sucess\n");
read(fd,&process_inter,1);
while(process_inter == 0);
for(i=0;i<5;i++)
{
printf("this is second process i=%d\n",i);
usleep(100);
}
while(1);
return 0;
}