无名管道和有名管道都存储于一段缓存,且必须读写两端同时打开,才能传输信息,无名管道只能应用于有亲缘的进程,而有管道可以应用于非亲缘的进程,他们是存储于缓存,所以当乌班图开关机以后,信息就不再了,如果你读走信息,它也不再了
pipe创建无名管道
int pipe(int pipefd[2]);
brief:创建一个管道,这个管道更像是半双工,在同一时间下,要么只读,要么只写,消息一但读走,就不存在了,由于是在linux内核创建的管道,所以并不会存在文件,也被称为无名管道,它只能用于具有亲缘关系的进程之间的通信(也是父子进程或者兄弟进程之间)。
param:pipefd[2],创建一个int型数组,传参给pipefd
return:返回两个文件标识符,[0]读,[1]写
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>
void main()
{
pid_t pid;
int fd[2];
char * buf = "Li jian hua";
int len = strlen(buf);
char *readbuf = (char *)malloc(sizeof(char)*len);
if(pipe(fd) == -1)
{
printf("no create guandao!");
exit(-1);
}
pid = fork();
if(pid > 0)
{
sleep(2);
printf("this is father\n");
close(fd[0]);
write(fd[1],buf,strlen(buf));
wait(NULL);
}
if(pid == 0)
{
close(fd[1]);
printf("this is son\n");
read(fd[0],readbuf,sizeof(char)*len);
printf("read from guandao : %s\n",readbuf);
exit(0);
}
}
输出结果:
read from guandao :Li jian hua
mkfifo创建有名管道
int mkfifo(const char * pathname,mode_t mode)
brief:创建一个有名管道,会生成一个节点,这个节点指向管道的缓冲区,通过open打开这个文件才会开始创建文件,但是它创建过后的文件,里面内容为0,它无视亲缘关系,可以用于非血缘关系,如果已经有mkfifo这个文件,就会出错
param:pathname,创建文件的绝对路径,如果该文件已存在,则创建失败,mode,给创建这个文件的权限
return:创建成功返回0,失败返回-1
注意:一定不要在共享文件夹创建,可能创建不成功
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>
void main()
{
pid_t pid;
int fd;
char *buf = "Aleen iverson";
int len = strlen(buf);
char *readbuf = (char *)malloc(sizeof(char )*len);
fd = mkfifo("./file",0600);
if(fd == -1)
{
printf("creat file lose!");
exit(-1);
}
fd = open("./file",O_RDWR);
pid = fork();
if(pid == -1)
{
printf("creat fork lose!");
exit(-1);
}
if(pid > 0)
{
sleep(2);
printf("this is father");
write(fd,buf,len);
lseek(fd,0,SEEK_SET);
wait(NULL);
}
if(pid == 0)
{
printf("this is son\n");
read(fd,readbuf,len);
printf("readbuf:%s\n",readbuf);
exit(0);
}
close(fd);
}
输出结果:
this is son
readbuf:Aleen iverson
this is father