接下来的一段时间需要去学习进程间的通信,又是全新的认识了,接着就是线程,我们的目标越来越近,完成我们的Linux学习任务也是指日可待,努力学习吧!
pipe:
这个命令也需要请出来我们的老演员man,使用man 2 pipe查看pipe命令如何使用:
知道该如何使用之后我们就需要知道运用在哪里?没错,就是我们的fork函数父子进程之中试试:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
//int pipe(int pipefd[2]);
int fd[2]; //0 read,1 write
int pid;
char buf[128];
if(pipe(fd) == -1)
{
printf("the pro error,open failed!\n");
}
pid=fork();
if(pid<0)
{printf("creat child fork failed!\n");}
else if(pid>0)
{
printf("this is father pro!\n");
close(fd[0]); //在父进程中关闭管道fd0
write(fd[1],"hello from father",strlen("hello from father"));//写操作,写入里面的字节到管道1
}
else
{
printf("this is child pro!\n");
close(fd[1]); //关闭写操作
read(fd[0],buf,128); //从管道fd0中读取到buf之中
printf("read from father: %s\n",buf);//输出打印
}
return 0;
}
让我们看看结果:
父进程中写入的东西,在子进程中也读取到了。 完成!这就是管道之间的通信。