慕運(yùn)維8597106 的學(xué)生作業(yè):
#include
#include
#include
#include
#include
#include
#include
#include
#define PATH "."
#define PRO_ID 99
#define MSG_TYPEA 100
#define MSG_TYPEB 200
#define MSG_SZ 64
struct msgbuf
{
long mtype;
char mtext[MSG_SZ];
};
void send_message(int msgid, int messageType, char *buf)
{
struct msgbuf msg;
msg.mtype = messageType;
strcpy(msg.mtext, buf);
int ret = msgsnd(msgid, &msg, strlen(msg.mtext) + 1, 0);
}
void receive_message(int msgid, struct msgbuf *rcv_msg, int messageType)
{
int ryptes = msgrcv(msgid, rcv_msg, MSG_SZ, messageType, 0);
if (ryptes == -1)
{
perror("[ERROR] msgrcv");
}
if (strcmp(rcv_msg->mtext, "quit") == 0)
{
printf("進(jìn)程%d下線了\n", messageType);
exit(EXIT_SUCCESS);
}
printf("進(jìn)程%d收到消息隊列中的數(shù)據(jù) 類型:%ld 內(nèi)容:%s\n", messageType, rcv_msg->mtype, rcv_msg->mtext);
}
int main(int argc, char const *argv[])
{
key_t key, msgid;
char buf[64] = {0};
int ret;
int cpidA, cpidB;
struct msgbuf rcv_msg;
int ryptes;
key = ftok(PATH, PRO_ID);
if (key == -1)
{
perror("[ERROR] ftok : ");
exit(EXIT_FAILURE);
}
msgid = msgget(key, IPC_CREAT | 0666);
if (msgid == -1)
{
perror("[ERROR] msgget : ");
exit(EXIT_FAILURE);
}
cpidA = fork();
if (cpidA == -1)
{
perror("[ERROR] fork");
exit(EXIT_FAILURE);
}
else if (cpidA == 0)
{
while (1)
{
receive_message(msgid, &rcv_msg, MSG_TYPEA);
}
}
else if (cpidA > 0)
{
cpidB = fork();
if (cpidB == -1)
{
perror("[ERROR] fork");
exit(EXIT_FAILURE);
}
else if (cpidB == 0)
{
while (1)
{
receive_message(msgid, &rcv_msg, MSG_TYPEB);
}
}
else if (cpidB > 0)
{
}
}
while (1)
{
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = '\0';
send_message(msgid, MSG_TYPEA, buf);
send_message(msgid, MSG_TYPEB, buf);
if (strcmp(buf, "quit") == 0)
{
waitpid(cpidA, NULL, 0);
waitpid(cpidB, NULL, 0);
exit(EXIT_SUCCESS);
}
}
return 0;
}
執(zhí)行結(jié)果
linux@linux:~/learn/chapter12/new/job1-16$ ./a.out
ls
進(jìn)程100收到消息隊列中的數(shù)據(jù) 類型:100 內(nèi)容:ls
進(jìn)程200收到消息隊列中的數(shù)據(jù) 類型:200 內(nèi)容:ls
ts
進(jìn)程100收到消息隊列中的數(shù)據(jù) 類型:100 內(nèi)容:ts
進(jìn)程200收到消息隊列中的數(shù)據(jù) 類型:200 內(nèi)容:ts
js
進(jìn)程100收到消息隊列中的數(shù)據(jù) 類型:100 內(nèi)容:js
進(jìn)程200收到消息隊列中的數(shù)據(jù) 類型:200 內(nèi)容:js
quit
進(jìn)程200下線了
進(jìn)程100下線了
linux@linux:~/learn/chapter12/new/job1-16$