#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MSG "Hello,this is test!!!"
int main()
{
int pipe_p[2];
int rv=-1;
pid_t pid;
char buf[1024];
int wstatus;
if(pipe(pipe_p)<0)
{
printf("Pipe is failure:%s\n",strerror(errno));
return -1;
}
if((pid=fork())<0)
{
printf("Fork() child failure:%s\n",strerror(errno));
return -2;
}
else if(pid==0)
{
printf("This is child\n");
memset(buf,0,sizeof(buf));
close(pipe_p[1]);//1 is write
rv=read(pipe_p[0],buf,sizeof(buf));
if(rv<0)
{
printf("Read failure:%s\n rv=%d\n",strerror(errno),rv);
return -3;
}
printf("Read data %d bytes from father:%s\n",rv,buf);
return 0;
}
close(pipe_p[0]);
if((rv=write(pipe_p[1],MSG,strlen(MSG)))<0)
{
printf("Write failure:%s\n",strerror(errno));
return -4;
}
printf("Parent start wait child process exit...\n");
wait(&wstatus);
return 0;
}
pipe函数会创建一个管道,其中fd[1]为写入数据,fd[0]为读取数据,该管道相当于一个缓冲区域,读取之后数据将不在存在。
在创建子进程之后,子进程会复制父进程的所有代码,包括起创建的fd[0],fd[1],所有这时有四个fd,要使用管道需要关闭不相关的fd才能运行。例如父进程要向子进程里写入数据,需要关闭父进程的fd[0]和关闭子进程的fd[1],让管道中仅存在一条线。
此外,使用wait函数是因为不能让父进程在子进程之前结束,wait用于等待子进程结束,回收并释放子进程资源
我们是在父进程中使用wait(),可以不让父进程先于其产生的子进程结束,因为如果父进程结束了,而子进程还没有结束,那这个进程就会变成一个“孤儿进程”,他会被init进程收养(进程号为1),并由init进程对它们完成状态收集工作。
当然如果子进程结束了,但是父进程没有调用wait或waitpid,那么子进程的资源就无法得到收集释放,这时候的子进程被称为“僵尸进程”,会占用系通资源,是非常不好的,危害很大