无名管道pipe和有名管道FIFO

定义:

1、管道是单向的,先进先出的,它把一个进程的输入和一个进程的输出连接在一起。

一个进程(写进程)在管道的尾部写入数据,另一个进程(读进程)在管道的头部读取数据

2、数据被一个进程读出后,将从管道中删除,其他进程将不能进行读取,当读空管道或在写入数据时管道已满将堵塞

3、管道包括有名管道和无名管道,无名管道只能用于父子进程之间的通信,有名管道可以用于一个系统中任意两个管道之间的通信

4、无名管道用pipe()函数创建,当一个管道创建时,会自动创建2个文件描述符,fd[0]用于读管道,fd[1]用于写管道

5、管道用于不同进程之间的通信,通常先创建一个管道,在通过fork()函数创建子进程,该子进程会继承父进程所创建的管道

6、必须在系统调用fork()函数前调用pipe()函数,否则将不会继承文件描述符

程序实例

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>


int main()
{
int fd[2];     //管道的2个文件描述符
char buf_r[100];
char *p_wbuf;
int r_num;


pid_t pid;     //

char str[100];


memset(buf_r,0,sizeof(buf_r));


if(pipe(fd) < 0)
{
perror("pipe error");
exit(-1);
}


if((pid = fork()) == 0)   //创建子进程成功
{
close(fd[1]);        //关闭写
sleep(2);


if((r_num = read(fd[0],buf_r,100)) > 0)
{
printf("%d numbers read from the pipe is :%s\n",r_num,buf_r);
close(fd[0]);
exit(0);
}
}


else if(pid > 0)
{
close(fd[0]);

printf("please input a string:\n");
scanf("%s",str);


if(write(fd[1],str,sizeof(str)) != -1)
{
printf("write pipe sucess\n");
}


close(fd[1]);
sleep(2);
waitpid(pid,NULL,0);


}






    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章