1.父进程创建消息队列和两个子进程p1和p2
2.子进程p1打开给定文件(如果没有,则创建文件),并向文件中写数据,写完关闭文件,然后向消息队列写入一条消息“ok”,目的是通知进程p2可以读取文件内容了。
3.子进程p2从消息队列读取消息,如果收到消息“ok”,则打开文件,读取文件内容,并将其输出道屏幕上,关闭文件。
代码部分:
/*
* quque.c
*
* Created on: Nov 10, 2016
* Author: koala
*/
/*
* quque.c
*
* Created on: Nov 10, 2016
* Author: koala
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/msg.h>
typedef struct mymsg
{
long mytype;
char mytext[128];
}mymsg;
int main()
{
pid_t fpid,pid1,pid2; //Declare father process and two children processes
fpid = getpid();
struct mymsg msg;
char buff[100];
//Get key identification
//Create a msg queue
int queueid = msgget(ftok(".",'t'),0660 | IPC_CREAT);
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 queue!", 1,sizeof("hello queue!")-1,fp );
fclose(fp);
fflush(fp);
strcat(msg.mytext ,"OK");
msgsnd(queueid,msg.mytext,sizeof(msg.mytext),IPC_NOWAIT);
}
}
wait(0);
if((pid2 = fork()) == 0)
{
printf("Children process2's PID is: %d and its father process's PID is: %d\n",getpid(),getppid());
msgrcv(queueid,msg.mytext,sizeof(msg.mytext),0,IPC_NOWAIT);
if(strcmp(msg.mytext,"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();
fclose(fpr);
}
}
}
pid_t childpid = wait(NULL);
printf("Process of %d exited\n",childpid);
return 0;
}
运行截图: