蠟筆小方哎 的學生作業(yè):
#include
#include
#include
#include
#include
#include
#include
#include
#define MSG_LEN 50
char buf[100];
long mtype_1 = 100;
long mtype_2 = 200;
struct msgbuf
{
long mtype;
char mtext[MSG_LEN];
};
int main()
{
key_t key = ftok(".", 'A');
if(key == -1)
{
perror("ftok() error!\n");
exit(-1);
}
printf("key = %d\n", key);
int msgid = msgget(key, IPC_CREAT | 0644);
if(msgid == -1)
{
perror("msgget() error!\n");
exit(-1);
}
printf("msgid = %d\n", msgid);
pid_t pid_1 = fork();
if(pid_1 == -1)
{
perror("fork() error!\n");
exit(-1);
}
else if(pid_1 == 0)
{
struct msgbuf msg;
while(1)
{
memset(msg.mtext, 0, MSG_LEN);
msgrcv(msgid, (void*)&msg, MSG_LEN, mtype_1, 0);
if(strcmp(msg.mtext, "quit") == 0)
{
break;
}
printf("in child process 1 recv: %s\n", msg.mtext);
}
printf("child process 1 quit!\n");
}
else
{
pid_t pid_2 = fork();
if(pid_2 == -1)
{
perror("fork() error!\n");
exit(-1);
}
else if(pid_2 == 0)
{
struct msgbuf msg;
while(1)
{
memset(msg.mtext, 0, MSG_LEN);
msgrcv(msgid, (void*)&msg, MSG_LEN, mtype_2, 0);
if(strcmp(msg.mtext, "quit") == 0)
{
break;
}
printf("in child process 2 recv: %s\n", msg.mtext);
}
printf("child process 2 quit!\n");
}
else
{
int flag = 0;
struct msgbuf msg;
while(1)
{
printf("Please input something: ");
memset(buf, 0, sizeof(buf));
memset(msg.mtext, 0, MSG_LEN);
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf)-1] = '\0';
strcpy(msg.mtext, buf);
if(strcmp(buf, "quit") == 0)
{
// 給兩個子進程都發(fā)送quit,再退出
msg.mtype = mtype_1;
msgsnd(msgid, (const void*)&msg, strlen(msg.mtext), 0);
msg.mtype = mtype_2;
msgsnd(msgid, (const void*)&msg, strlen(msg.mtext), 0);
break;
}
if(flag == 0)
{
msg.mtype = mtype_1;
flag = 1;
}
else
{
msg.mtype = mtype_2;
flag = 0;
}
msgsnd(msgid, (const void*)&msg, strlen(msg.mtext), 0);
}
wait(NULL);
wait(NULL);
}
}
return 0;
}