Note that there are some explanatory texts on larger screens.

plurals
  1. POSystem V Msg Queues on Linux don't work as expected
    text
    copied!<p>I have the following application which replicates an issue I'm having in a larger application with system v message queues. basically, the main function generates a key, then creates a message queue with msgget(). Then 3 forks are spawned, each with a different id. each of them runs msgrcv with a different posative number (so they are waiting for different messages).</p> <p>Main then sleeps for a few seconds a sends a message to id = 3. However it <em>isn't</em> the third thread that wakes up but a different one instead. This code is completely isolated so you can try it out yourself. What's wrong with this code?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/ipc.h&gt; #include &lt;sys/msg.h&gt; #include &lt;sys/wait.h&gt; 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 &lt; 4; i++) // &lt;- NOTE: 1 -&gt; 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, &amp;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, &amp;dummy, sizeof(struct dummy_struct), id, 0) == -1) printf("error in msgrcv\n"); else printf("thread %i got %s back\n", id, dummy.message); } </code></pre> <p>If I wait for 2 that means messages whose struct contains a mtype set to <em>exactly</em> 2. 3 for 3 and so one. My point of reference was this guide: <a href="http://www.ecst.csuchico.edu/~beej/guide/ipc/mq.html" rel="nofollow noreferrer">http://www.ecst.csuchico.edu/~beej/guide/ipc/mq.html</a>. Can anyone help please? (you may need to modify the ftok line of code to point to a valid file on your own machine to test successfully). I'm running Fedora 10 on an EeePC 1000H</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload