#include "head.h"
/*
使用消息队列实现进程间相互通信
ftok msgget msgsnd msgcrv msgctrl
*/
struct msgbuf
{
long mtype; /* message type, must be > 0 */
char mtext[1]; /* message data */
};
//发送消息类型
#define MSGTYPE 10
//接收消息类型
#define MSSNYPE 12
//内容长度
#define SIZE (sizeof(struct msgbuf) - sizeof(long))
#define ERRMSG(errmsg) do{\
printf(" %s : %s (%d):",__FILE__,__func__,__LINE__);\
printf(errmsg);\
exit(-1);\
} while(0)
//创建key消息队列
int create_msp()
{
//申请key
int fk = ftok("./", 'k');
if (fk > 0)
{
ERRMSG("ftok\n");
// return -1;
}
printf("key = %#x\n", fk);
//创建消息队列
int msgid = msgget(fk, IPC_CREAT | 0664);
if (msgid == -1)
{
perror("msgget");
return -1;
}
return msgid;
}
//发送消息,成功返回0 失败返回-1
int send_msg(int msgid)
{
struct msgbuf buf;
buf.mtype = MSGTYPE;
while (1)
{
printf("请输入消息内容:");
scanf("%s", buf.mtext);
printf("\n");
int result = msgsnd(msgid, &buf, SIZE, 0);
if (result == -1)
{
return -1;
}
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
return 0;
}
//获取消息
int get_msg(int msqId)
{
while (1)
{
struct msgbuf buf;
// buf.mtype = MSSNYPE;
msgrcv(msqId, &buf, SIZE, MSSNYPE, 0);
printf("收到消息:%s\n", buf.mtext);
if (strcmp(buf.mtext, "quit") == 0)
{
pthread_exit(NULL);
break;
}
}
}
//子线程接收消息
void *task(void *arg)
{
int * id = (int *)arg;
//子线程
get_msg (*id);
}
int main(int argc, char const *argv[])
{
//获取队列id
int msp_id = create_msp();
pthread_t pt = -1;
int pts = pthread_create(&pt, NULL, task, &msp_id);
if (pts != 0)
{
printf("pthread create error \n");
return -1;
}
//主线程发送消息
send_msg(msp_id);
//回收分支线程资源
pthread_join(pt, NULL);
return 0;
}
#include "head.h"
/*
使用消息队列实现进程间相互通信
ftok msgget msgsnd msgcrv msgctrl
*/
struct msgbuf
{
long mtype; /* message type, must be > 0 */
char mtext[1]; /* message data */
};
//发送消息类型
#define MSGTYPE 12
//接收消息类型
#define MSSNYPE 10
//内容长度
#define SIZE (sizeof(struct msgbuf) - sizeof(long))
//创建key消息队列
int create_msp()
{
//申请key
int fk = ftok("./", 'k');
if (fk == -1)
{
perror("ftok");
return -1;
}
printf("key = %#x\n", fk);
//创建消息队列
int msgid = msgget(fk, IPC_CREAT | 0664);
if (msgid == -1)
{
perror("msgget");
return -1;
}
return msgid;
}
//发送消息,成功返回0 失败返回-1
int send_msg(int msgid)
{
struct msgbuf buf;
buf.mtype = MSGTYPE;
while (1)
{
printf("请输入消息内容:");
scanf("%s", buf.mtext);
printf("\n");
int result = msgsnd(msgid, &buf, SIZE, 0);
if (result == -1)
{
return -1;
}
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
return 0;
}
//获取消息
int get_msg(int msqId)
{
while (1)
{
struct msgbuf buf;
buf.mtype = MSSNYPE;
msgrcv(msqId, &buf, SIZE, MSSNYPE, 0);
printf("收到消息:%s\n", buf.mtext);
if (strcmp(buf.mtext, "quit") == 0)
{
pthread_exit(NULL);
break;
}
}
}
//子线程接收消息
void *task(void *arg)
{
int *id = (int *)arg;
//子线程
get_msg(*id);
}
int main(int argc, char const *argv[])
{
//获取队列id
int msp_id = create_msp();
pthread_t pt = -1;
pt = pthread_create(&pt, NULL, task, &msp_id);
if (pt != 0)
{
printf("pthread create error \n");
return -1;
}
//主线程发送消息
send_msg(msp_id);
//回收分支线程资源
pthread_join(pt, NULL);
return 0;
}