一、问题描述
1.父进程创建管道和两个子进程p1和p2
2.子进程p1打开给定文件(如果没有,则创建文件),并向文件中写数据,写完关闭文件,然后向管道写入一条消息“ok",目的是通知进程p2可以读取文件内容了。
3.子进程p2通过管道读取消息,如果消息是“ok”,则打开文件,读取文件内容,并将其输出到屏幕上,关闭文件。
二、代码
/*
create by : Koalazb
...
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
int filedes[2]; //Declare read or write parameter
char buf[100]; //Declare buffer segment for pipe
char buff[100]; //Declare buffer for file
pid_t fpid,pid1,pid2; //Declare father process and two children processes
fpid = getpid();
pipe(filedes); //Create a pipe
printf("The father process's PID is: %d\n",fpid);
char dir[100];//Declare file direction
if((pid1 = fork()) == 0)
{
printf("Children process1's PID is: %d and its father process's PID is: %d\n",getpid(),getppid());
FILE *fp;
printf("Please enter the file direction:\n");
fgets(dir,sizeof(dir)-1,stdin);
fp = fopen(dir,"w+");//Open file"hello pipe.txt",if failed then create
if(fp == NULL)
{
printf("The file cannot be open or create!\n");
}
else
{
//Write data to file
fwrite ("hello pipe!", 1,sizeof("hello pipe!")-1,fp );
fclose(fp);
fflush(fp);
char s[] = "OK";
write(filedes[1], s, sizeof(s));
close(filedes[0]);
close(filedes[1]);
}
}
if((pid2 = fork()) == 0)
{
printf("Children process2's PID is: %d and its father process's PID is: %d\n",getpid(),getppid());
read(filedes[0],buf,sizeof(buf));
if(strcmp(buf,"OK"))
{
FILE *fpr;
fpr = fopen(dir,"r");
if(fpr == NULL)
{
printf("The file does not exist!\n");
}
else
{
while(fgets(buff,1024 ,fpr)!= NULL)
{
fprintf(stderr,"%s",buff);
}
getchar();
printf("\n");
fclose(fpr);
}
close(filedes[0]);
close(filedes[1]);
}
}
pid_t childpid =wait(NULL);
printf("Process of %d exited\n",childpid);
return 0;
}