Receiving SysV messages using fork()

329 views Asked by At

I'm trying to receive a series of messages I sent with msgsnd in a series of fork()s. I can tell the messages sent ok, but receiving them has been a problem. Here's the problem part of the code, using three messages as an example:

for(j=1;j<4;j++)
{
    if(!(pid_A = fork()))
    {
        msgLen = msgrcv(msqid, &rec, sizeof(struct u_msgbuf) - sizeof(long), 0,0);
        if(msgLen == -1)
        {
            printf("%i - %s.\n", j, strerror(errno));
            exit(0);
        }
        else
        {
            printf("%i - %s.\n", j, rec.word);
            exit(0);
        }
    }
}

If I write code similar to this without a fork(), it works fine, so I know the fork() is messing with my message queue in a way I don't understand. Could someone tell me why this won't work in a fork(), and how I could code this in such a way that my fork() will receive messages properly?

Edit: What I am getting is this: first fork to process runs fine, second rarely does, third always fails. The errno is getting set to 22, which is Invalid Argument.


Update (declarations used):

struct u_msgbuf
{
  long mtype;
  char word[15];
};

struct u_msgbuf rec; 
0

There are 0 answers