IPC message queue does not work with forked process

I am trying to use an IPC message queue with a forked process by passing a pointer to a dynamically allocated string, but it does not work.

This is a simple test that I did. It does not print the line received from the queue. But if I try to remove fork(), it works fine.

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MSGSZ     128

typedef struct msgbuf {
    long    mtype;
    char    *mtext;
} message_buf;

int
main ()
{
    int msqid;
    char *p;
    key_t key = 129;

    message_buf sbuf, rbuf;
    p = (char *) malloc(sizeof(char) * MSGSZ);

    if ((msqid = msgget(key, IPC_CREAT|0666)) < 0) {
        perror("msgget");
        exit(1);
    }

    if (fork() == 0) {
        strcpy(p, "Did you get this?");
        sbuf.mtype = 1;
        sbuf.mtext = p;

        if (msgsnd(msqid, &sbuf, MSGSZ, IPC_NOWAIT) < 0) {
            perror("msgsnd");
            exit(1);
        }
    }
    else {
        sleep(1);

        if (msgrcv(msqid, &rbuf, MSGSZ, 0, 0) < 0) {
            perror("msgrcv");
            exit(1);
        }

        printf("Forked version: %s\n", rbuf.mtext);
        msgctl(msqid, IPC_RMID, NULL);
    }
}
+4
source share
1 answer

, . / . , , , msgbuf.mtext MSGSZ ( Undefined Behavior).

, . , message_buf :

typedef struct msgbuf {
    long    mtype;
    char    mtext[MSGSZ];
} message_buf;

strcpy mtext:

strcpy(sbuf.mtext, "Did you get this?");

:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MSGSZ     128

typedef struct msgbuf {
    long    mtype;
    char    mtext[MSGSZ];
} message_buf;

int
main (void)
{
    int msqid;
    key_t key = 129;

    message_buf sbuf, rbuf;

    if ((msqid = msgget(key, IPC_CREAT|0666)) < 0) {
        perror("msgget");
        exit(1);
    }

    if (fork() == 0) {
        strcpy(sbuf.mtext, "Did you get this?");
        sbuf.mtype = 1;

        if (msgsnd(msqid, &sbuf, MSGSZ, IPC_NOWAIT) < 0) {
            perror("msgsnd");
            exit(1);
        }
    }
    else {
        sleep(1);

        if (msgrcv(msqid, &rbuf, MSGSZ, 0, 0) < 0) {
            perror("msgrcv");
            exit(1);
        }

        printf("Forked version: %s\n", rbuf.mtext);
        msgctl(msqid, IPC_RMID, NULL);
    }
}
+2

Source: https://habr.com/ru/post/1622064/


All Articles