/*
1.获取key:ftok()
2.获取消息实例:msgget()
3.收发消息:msgsnd(),msgrcv()
4.销毁消息实例:msgctl()
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <memory.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
typedef struct{
long type;
char msg_buf[1024];
}msg_def;
int main(int argc, char** argv)
{
key_t key;
int msg_id = 0;
size_t snd_len = 0;
int res = 0;
if (argc < 2)
{
printf("Usage: %s key\n", argv[0]);
exit(-1);
}
key = ftok(argv[1], 0);
msg_id = msgget(key, IPC_CREAT | 0777);
if (msg_id < 0)
{
perror("msgget error");
exit(-1);
}
printf("msg_id=%d\n", msg_id);
msg_def msg;
memset(&msg, 0x00, sizeof(msg_def));
msg.type=1;
memcpy(msg.msg_buf, "hello", sizeof(msg.msg_buf)-1);
snd_len = sizeof(msg)-sizeof(long);
res = msgsnd(msg_id, (const void*)&msg, snd_len, IPC_NOWAIT);
if (res < 0)
{
perror("msgsnd error");
exit(-2);
}
msg.type=2;
memcpy(msg.msg_buf, "world", sizeof(msg.msg_buf)-1);
res = msgsnd(msg_id, (const void*)&msg, snd_len, IPC_NOWAIT);
if (res < 0)
{
perror("msgsnd error");
exit(-2);
}
struct msqid_ds ds;
res = msgctl(msg_id, IPC_STAT, &ds);
if (res < 0)
{
perror("msgctl error");
}
printf("msg snd total is %d\n", ds.msg_qnum);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <memory.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
typedef struct{
long type;
char msg_buf[1024];
}msg_def;
int main(int argc, char** argv)
{
key_t key;
int msg_id = 0;
size_t rcv_len = 0;
int res = 0;
long type = 0;
if (argc < 3)
{
printf("Usage: %s key type\n", argv[0]);
exit(-1);
}
type = atoi(argv[2]);
key = ftok(argv[1], 0);
msg_id = msgget(key, IPC_CREAT | 0777);
if (msg_id < 0)
{
perror("msgget error");
exit(-1);
}
printf("msg_id=%d\n", msg_id);
msg_def msg;
memset(&msg, 0x00, sizeof(msg_def));
rcv_len = sizeof(msg)-sizeof(long);
res = msgrcv(msg_id, (void*)&msg, rcv_len, type, 0);
if (res < 0)
{
perror("msgsnd error");
exit(-2);
}
printf("type=%d, msg_buf=%s, msg_len=%d\n", msg.type, msg.msg_buf, rcv_len);
struct msqid_ds ds;
res = msgctl(msg_id, IPC_STAT, &ds);
if (res < 0)
{
perror("msgctl error");
}
printf("msg snd total is %d\n", ds.msg_qnum);
return 0;
}
运行:
1…/my_msg_snd /etc/passwd
msg_id=131072
msg snd total is 2
2.ipcs -q
------ Message Queues --------
key msqid owner perms used-bytes messages
0x00015beb 131072 zhangsan 777 2048 2
3…/my_msg_rcv /etc/passwd 1
msg_id=131072
type=1, msg_buf=hello, msg_len=1024
msg snd total is 1
4.ipcs -q
------ Message Queues --------
key msqid owner perms used-bytes messages
0x00015beb 131072 zhangyue 777 1024 1
5…/my_msg_rcv /etc/passwd 2
msg_id=131072
type=2, msg_buf=world, msg_len=1024
msg snd total is 0
可以通过命令删除消息队列:ipcrm -q 131072
代码删除:msgctl(msg_id, IPC_RMID, &ds);