3、建立两个.c 建立子父进程,父进程发送消息到队列,子进程读取队列,另一个同样。
#include <myhead.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
#define leng sizeof(struct msgbuf) - sizeof(long)
int main(int argc, const char *argv[])
{
key_t key = ftok("./",'J');
if(key==-1)
{
perror("ftok");
return -1;
}
printf("键:%#x\n",key);
int msgID = msgget(key,IPC_CREAT|0664);
if(msgID==-1)
{
perror("msget");
return -1;
}
printf("msgid = %d\n",msgID);
pid_t pid = fork();
if(pid>0)
{
struct msgbuf send;
while(1)
{
printf("请输入消息类型:");
scanf("%ld",&send.mtype);
getchar();
printf("请输入消息的内容:");
fgets(send.mtext,sizeof(send.mtext),stdin);
msgsnd(msgID,&send,leng,0);
if(strcmp(send.mtext,"quit\n")==0)
{
break;
}
}
if(msgctl(msgID,IPC_RMID,NULL)==-1)
{
printf("删除队列失败\n");
return -1;
}
}
else if(pid==0)
{
struct msgbuf rcv;
while(1)
{
msgrcv(msgID,&rcv,leng,0,0);
printf("%s\n",rcv.mtext);
if(strcmp(rcv.mtext,"quit\n")==0)
{
break;
}
}
}
else
{
perror("fork");
return -1;
}
return 0;
}
#include <myhead.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
#define leng (sizeof(struct msgbuf) - sizeof(long))
int main(int argc, const char *argv[])
{
key_t key1 = ftok("./", 'J'); // 与原程序相同的键
key_t key2 = ftok("./", 'K'); // 新的键
if (key1 == -1 || key2 == -1)
{
perror("ftok");
return -1;
}
printf("键1:%#x\n键2:%#x\n", key1, key2);
int msgID1 = msgget(key1, IPC_CREAT | 0664);
int msgID2 = msgget(key2, IPC_CREAT | 0664);
if (msgID1 == -1 || msgID2 == -1)
{
perror("msgget");
return -1;
}
printf("msgid1 = %d\nmsgid2 = %d\n", msgID1, msgID2);
pid_t pid = fork();
if (pid > 0)
{
struct msgbuf send;
while (1)
{
printf("请输入消息类型:");
scanf("%ld", &send.mtype);
getchar();
printf("请输入消息的内容:");
fgets(send.mtext, sizeof(send.mtext), stdin);
msgsnd(msgID2, &send, leng, 0); // 发送到 msgID2
if (strcmp(send.mtext, "quit\n") == 0)
{
break;
}
}
// 不在这里删除消息队列,让另一个程序来删除
}
else if (pid == 0)
{
struct msgbuf rcv;
while (1)
{
msgrcv(msgID1, &rcv, leng, 0, 0); // 从 msgID1 接收
printf("收到消息:%s", rcv.mtext);
if (strcmp(rcv.mtext, "quit\n") == 0)
{
break;
}
}
}
else
{
perror("fork");
return -1;
}
return 0;
}
1777

被折叠的 条评论
为什么被折叠?



