新网$网站优化,站酷网app,网站侧边栏菜单,个人制作的网站模板实现消息队列实现AB进程对话。
a.A进程发送一句话后#xff0c;B进程接收到打印。然后B进程发送一句话#xff0c;A进程接收后打印
b.重复上述步骤。直到AB接收或者发送完quit后#xff0c;结束AB进程
A:
#include stdio.h
#include sys/types.h
#inclu…实现消息队列实现AB进程对话。
a.A进程发送一句话后B进程接收到打印。然后B进程发送一句话A进程接收后打印
b.重复上述步骤。直到AB接收或者发送完quit后结束AB进程
A:
#include stdio.h
#include sys/types.h
#include sys/ipc.h
#include sys/msg.h
#include string.h
#include stdlib.htypedef struct
{long mtype; // 消息类型 必须 0;char mtext[32]; // 消息内容
}msgp;int main(int argc, const char *argv[])
{key_t key ftok(/home/ubuntu/,1);if(key 0){perror(ftok);return -1;}// 创建消息队列int msqid msgget(key, IPC_CREAT|0664);if( msqid 0){perror(msgget);return -1;}// 消息打包发送msgp msg;ssize_t res 0;while(1){
// ************** A 写 ******************* printf(请输入消息类型:);scanf(%ld, msg.mtype);getchar();if(msg.mtype 0){break;}printf(请输入消息内容:);fgets(msg.mtext, sizeof(msg.mtext), stdin);msg.mtext[strlen(msg.mtext) - 1] \0;if( msgsnd(msqid, msg, sizeof(msg.mtext), IPC_NOWAIT) 0 ){perror(msgsnd);return -1;}if( strcmp(msg.mtext,quit) 0 ){break;}printf(消息发送成功!!!\n);printf(消息队列如下:\n);system(ipcs -q);// ************** A 接收 ***************************printf(A等待接收.....\n);res msgrcv(msqid, msg, sizeof(msg.mtext), 0, 0);if( res 0 ){perror(msgsnd);// break;}if( strcmp(msg.mtext,quit) 0){break;}printf(A--消息接收成功! );printf(A--接受消息如下:\n);printf(res%ld | mtype%ld : mtext%s \n,res, msg.mtype, msg.mtext);printf(------------------------------------------\n);}return 0;
}
B
#include stdio.h
#include sys/types.h
#include sys/ipc.h
#include sys/msg.h
#include string.h
#include stdlib.h#define MSG_EXCEPT 020000typedef struct
{long mtype; // 消息类型 必须 0;char mtext[32]; // 消息内容
}msgp;int main(int argc, const char *argv[])
{key_t key ftok(/home/ubuntu/,1);if(key 0){perror(ftok);return -1;}// 创建消息队列int msqid msgget(key, IPC_CREAT|0664);if( msqid 0){perror(msgget);return -1;}// 消息打包发送msgp msg;ssize_t res 0;while(1){
// ****************** B 接收 *******************printf(B等待接收.....\n); res msgrcv(msqid, msg, sizeof(msg.mtext), 0, 0);if( res 0 ){perror(msgsnd);}if( strcmp(msg.mtext,quit) 0){break;}printf(B--消息接收成功! );printf(B--接受消息如下:\n);printf(res%ld | mtype%ld : mtext%s \n,res, msg.mtype, msg.mtext);printf(------------------------------------------\n); // ************** B 写 ******************* printf(请输入消息类型:); scanf(%ld, msg.mtype);getchar();if(msg.mtype 0){break;}printf(请输入消息内容:);fgets(msg.mtext, sizeof(msg.mtext), stdin);msg.mtext[strlen(msg.mtext) - 1] \0;if( msgsnd(msqid, msg, sizeof(msg.mtext), IPC_NOWAIT) 0 ){perror(msgsnd);return -1;}if( strcmp(msg.mtext,quit) 0 ){break;}printf(消息发送成功!!!\n);printf(消息队列如下:\n);system(ipcs -q);}
/* // 删除消息队列if( msgctl(msqid, IPC_RMID, NULL) 0 ){perror(msgctl);return -1;}printf(删除消息队列成功!!!\n);system(ipcs -q);
*/return 0;
}