前几天学习了管道内容,课本上只有无名管道的单工程序,老师说管道也可以进行双向通信,因此自己练习一下双向通信:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
pid_t pid;
int pipe1[2],pipe2[2];
char str[40];
if((pipe(pipe1))==-1)
{
perror("pipe is failed!!!");
exit(EXIT_FAILURE);
}
if((pipe(pipe2))==-1)
{
perror("pipe is failed!!!");
exit(EXIT_FAILURE);
}
if((pid=fork())<0)
{
perror("fork is failed!!!\n");
exit(EXIT_FAILURE);
}
else if(pid==0)
{
close(pipe1[0]);
close(pipe2[1]);
printf("I am a child process!\n");
if(write(pipe1[1],"child process wtite data to pipe1\n",40)!=-1)
printf("write data to pipe1 is sucess\n");
read(pipe2[0],str,40);
printf("read pipe2=%s",str);
close(pipe1[1]);
close(pipe2[0]);
}
else if(pid>0)
{
sleep(3);
close(pipe1[1]);
close(pipe2[0]);
printf("I am a father process!\n");
write(pipe2[1],"parent process write data to pipe2\n",40);
printf("write data to pipe2 is success\n");
read(pipe1[0],str,40);
printf("read pipe1=%s",str);
close(pipe2[1]);
close(pipe1[0]);
waitpid(pid,NULL,0);
}
return 0;
}
管道的作用是将第一个进程的输出作为第二个进程的输入。
在无名管道单向通信中,pipe[ 2 ] 数组中,pipe[ 0 ] 表示读端,pipe[ 1 ] 表示写端,例如在进行文件读入管道时,首先应该关闭pipe[ 1 ] 写端,打开读端pipe[ 0 ],采用read( int pipeno,char *str,sizeof(sizeof)) 进行读,第一个参数为管道描述符,参数二是字符串,参数三是字符串长度。一定别忘了之后还要关闭读端。在管道中进行写文件时与读端类似。
而双向通信只是创建两个数组,表示两个管道
下面这个是兄弟间的单向通信:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
int main(int argc,char *argv[])
{
pid_t pid1,pid2;
int pipes[2];
char str[20];
if(pipe(pipes)==-1)
{
perror("pipe is error\n");
exit(EXIT_FAILURE);
}
pid1=fork();
if(pid1<0)
printf("Fork pid1 is error\n");
else if(pid1==0)
{
close(pipes[0]);
if((write(pipes[1],"We are brothers\n",20))==-1)
{
perror("write is error\n");
exit(EXIT_FAILURE);
}
else
printf("write data to pipe is success\n");
close(pipes[1]);
}
else
{
pid2=fork();
if(pid2<0)
printf("Fork pid2 is error\n");
else if(pid2==0)
{
close(pipes[1]);
if((read(pipes[0],str,20))==-1)
{
perror("read to pipe is error\n");
exit(EXIT_FAILURE);
}
else
printf("read from pipe = %s",str);
close(pipes[0]);
}
}
return 0;
}
关于子进程的创建采用上一篇的方法和原理。