我有以下应用程序,它复制了我在具有系统 v 消息队列的大型应用程序中遇到的问题。基本上,主函数生成一个密钥,然后使用 msgget() 创建一个消息队列。然后产生了 3 个分叉,每个分叉都有不同的 id。他们每个人都使用不同的正数运行 msgrcv(因此他们正在等待不同的消息)。
然后 Main 休眠几秒钟 a 向 id = 3 发送一条消息。但是唤醒的不是第三个线程,而是另一个线程。此代码是完全隔离的,因此您可以自己尝试。这段代码有什么问题?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/wait.h>
struct dummy_struct {
long mtype;
char message[255];
};
int msg_queue_id;
void recv_thread(int id);
int main(int argc, char **argv)
{
int i;
key_t key;
struct dummy_struct dummy = { 3, "hello" };
//create a unique key
if (key = ftok("/mnt/mydocuments/code/sys_v_fork_test/main.c", 'a') == -1)
{
printf("ftok didn't work\n");
exit(1);
}
//create the unix sys 5 message queue
if ((msg_queue_id = msgget(key, 0644 | IPC_CREAT)) == -1)
{
printf("msgget failed\n");
exit(1);
}
else
printf("my message queue id: %i\n", msg_queue_id);
//fork off multiple recievers
for (i = 1; i < 4; i++) // <- NOTE: 1 -> 4
{
if (fork() == 0)
recv_thread(i);
}
printf("sleeping\n");
sleep(5);
//wait a little then send a message
printf("sending message\n");
if (msgsnd(msg_queue_id, &dummy, sizeof(struct dummy_struct), 0) == -1)
{
printf("msgsnd failed\n");
}
printf("main thread exiting");
_exit(0);
}
void recv_thread(int id)
{
struct dummy_struct dummy;
printf("recv_thread with id: %i\n", id);
if (msgrcv(msg_queue_id, &dummy, sizeof(struct dummy_struct), id, 0) == -1)
printf("error in msgrcv\n");
else
printf("thread %i got %s back\n", id, dummy.message);
}
如果我等待 2,则表示其结构包含设置为 2 的 mtype 的消息。 3 表示 3,依此类推。我的参考点是本指南: http: //www.ecst.csuchico.edu/~beej/guide/ipc/mq.html。有人可以帮忙吗?(您可能需要修改 ftok 代码行以指向您自己机器上的有效文件才能成功测试)。我在 EeePC 1000H 上运行 Fedora 10