首先管道是进程之间的一个单向数据流,它的数据流向由内核管理,只能从一个进程流向另外一个进程,一个进程向管道写入数据,另外一个进程从这个管道读取数据。
在使用管道(无名管道)时,只能用在父子进程或者亲属进程之间,若要用在任意进程之间则需要使用FIFO(有名管道)
而在系统调用的时候,管道的读端和写端就以文件的方式呈现给我们,通过pipe()函数创建管道,我们可以得到读端文件和写端文件的fd,然后和文件编程一样通过read,write就可以实现读取写入数据。但与文件编程稍许不同就是,文件编程后文件的内容还存在,但是使用管道读取后,管道里的相应内容就消失了。
现在就来实现一个父进程通过管道写数据,子进程通过管道读数据的程序
1.创建管道 pipe()
2.创建子进程 fork()
3.对读端文件,写端文件进行文件编程 read(), write()
#include
#include
#include
#include
#include
#include
void main()
{
int pfd[2], res;
pid_t pid;
char *p = "I am kaito!", k[100];
res = pipe(pfd);
if(res == -1)
printf("Create the pipe failed!\n");
pid = fork();
if(pid == 0)
{
printf("This is the child process!\n");
res = read(pfd[0], k, strlen(p) + 1);
printf("The context from the pipe is:%s\nThe number of character is %d\n", k, res);
close(pfd[0]);
close(pfd[1]);
exit(0);
}
else
{
printf("This is the parent process!\n");
write(pfd[1], p, strlen(p) + 1);
wait(NULL);
exit(0);
}
}
显示结果为