代码功能描述:
1.主进程创建管道和两个子进程。
2.子进程p1实现文件的访问并向文件中写入字符串,并向管道写端写入ok消息。
3.子进程p2实现管道信息的读取,判断消息内容是不是ok
,如果是则打开p1创建的文件,并把字符串的内容打印出来。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
//这个函数用来实现子进程p1的需求
void creatAndWriteFile(){
//定义一个文件名叫file的文件指针
FILE *file;//新建一个文件
if((file = fopen("桌面:\\gucheng.txt","w")) == NULL){//文件打开不成功
printf("文件打开失败");
exit(1);
}
else{
printf("文件打开成功...\n");
printf("现在开始向文件中写入字符串...\n");
fputs("这是文件中 <顾程>写来测试的字符串,哈哈哈",file);
printf("向文件中写入字符串成功...\n");
}
printf("关闭文件...\n");
fclose(file);
}
//实现子进程p2的需求
void judgeAndPrintFileText(char *readBuffer,char *testMsg){
//调用strcmp()函数实现两个字符串的比较
if((strcmp(readBuffer,testMsg)) == 0){
printf("接受消息成功,管道中读到的消息是:ok\n");
//接下来打开进程p1建立的文件,并把文件内容输出在屏幕上
FILE *file;//新建一个文件
if((file = fopen("桌面:\\gucheng.txt","r")) == NULL){//文件打开不成功
printf("文件打开失败");
exit(1);
}
else{
while(!feof(file)){
char textArr[100];
if(fgets(textArr,100,file) != NULL){
printf("接下来打印出文件中的内容:\n");
printf("\n");
printf(textArr);
printf("\n");
printf("\n");
}
}
fclose(file);
}
}
}
//用来实现子进程的功能
void childFunction(int i,int *fileds){//参数fileds用来传递管道信息,要用指针
switch(i)
{
case 1:{
printf("创建子进程p1成功...\n");
//调用creatAndWriteFile函数
creatAndWriteFile();
//向管道中写入一条"ok"消息
char msg[] = "ok";
write(fileds[1],msg,sizeof(msg));
close(fileds[1]);//关闭管道的写端
printf("向管道中写入ok信息成功...\n");
//break语句是跳出了当前的switch
break;
}
case 2:{
printf("创建子进程p2成功...\n");
char readBuffer[80];//用来存储从管道中读取的信息
//读取管道中的消息并存到readBuffer中
read(fileds[0],readBuffer,sizeof(readBuffer));
//判断管道传送的信息是否是ok
char testMsg[] = "ok";
//调用judgeAndPrintFileText()函数
judgeAndPrintFileText(readBuffer,testMsg);
}
break;
}
//每次case结束之后都会执行,目的是为了结束当前的子进程
exit(0);
}
//主函数
int main()
{
//新建管道
int fileds[2];
pipe(fileds);//创建管道的时候直接pipe(fileds).
printf("创建管道成功...\n");
int i;
for(i=1;i<=2;i++){
pid_t child;
child=fork();//调用fork函数来创建子进程
//创建失败
if(child==-1){
printf("Error happened in fork function!\n");
return 0;
}
//子进程的返回值为0,
else if(child==0){
//printf("process ID is %d:\n",getpid());
//调用函数实现各个子进程的功能
childFunction(i,&fileds);
}
}
for(i=0;i<2;i++){
//父进程等待子进程的退出
pid_t cpid=wait(NULL);
printf("The process %d exit\n",cpid);
}
//最后父进程退出
printf("The NO.1 parent process ID is %d exit\n",getpid());
return 0;
}