北城半夏4806197 的学生作业:
#include
#include
#include
#include
#include
#include
#include
#define PATHNAME "."
#define PRO_ID 10
#define MSG_TYPE1 100
#define MSG_TYPE2 200
#define MSG_SZ 64
struct msgbuf{
long mtype;
char mtext[MSG_SZ];
};
int main(int argc, const char *argv[])
{
key_t key;
int msgid,ret;
struct msgbuf msg;
key = ftok(PATHNAME,PRO_ID);
if(key == -1){
perror("fotk(): ");
exit(EXIT_FAILURE);
}
msgid = msgget(key,IPC_CREAT | 0666);
if(msgid == -1)
{
perror("msgget(): ");
exit(EXIT_FAILURE);
}
printf("msg id : %d\n",msgid);
pid_t cpid1 = fork();
if(cpid1 == -1)
{
perror("[ERROR] fork():");
}
else if(cpid1 == 0){
struct msgbuf process;
while(1)
{
ret = msgrcv(msgid,(void*)&process,MSG_SZ,MSG_TYPE1,0);
if(ret == -1)
{
perror("[ERROR] msgcrv():");
exit(EXIT_FAILURE);
}
printf("A Process get \n",process.mtext);
}
}
else if(cpid1 > 0)
{
pid_t cpid2 = fork();
if(cpid2 == -1)
{
perror("[ERROR] fork():");
exit(EXIT_FAILURE);
}
else if(cpid2 == 0)
{
struct msgbuf process;
while(1)
{
ret = msgrcv(msgid,(void*)&process,MSG_SZ,MSG_TYPE2,0);
if(ret == -1)
{
perror("[ERROR] msgcrv():");
exit(EXIT_FAILURE);
}
printf("B Process get \n",process.mtext);
}
}
else if(cpid2 > 0)
{
struct msgbuf msgsand;
while(1)
{
printf("type:\n");
scanf("%ld",&msgsand.mtype);
printf("buf:\n");
scanf("%s",msgsand.mtext);
ret = msgsnd(msgid,(const void *)&msgsand,strlen(msgsand.mtext) + 1,0);
}
}
}
return 0;
}