Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending buffer through message queue

Hi I'm writing a program that sends a set of bytes through a message queue like so ...

#include <sys/msg.h>
#include <stddef.h>

key_t key;
int msqid;
struct pirate_msgbuf pmb = {2, { "L'Olonais", 'S', 80, 10, 12035 } };

key = ftok("/home/beej/somefile", 'b');
msqid = msgget(key, 0666 | IPC_CREAT);

/* stick him on the queue */
msgsnd(msqid, &pmb, sizeof(struct pirate_msgbuf) - sizeof(long), 0);

The above example is a simple program from beejs website that resembles mine.

What I'm doing however is sending a message with a struct like so ...

struct msg_queue{

    long message_type;
    char * buffer;

}

Now before I send my msg_queue, I created some alternative buffer that contains all sorts of information including null characters and such. Now when I do something like this ...

struct msg_queue my_queue;
my_queue.message_type = 1;
my_queue.buffer = "My message";
msgsnd(mysqid, &pmb, sizeof(struct msg_queue) - sizeof(long), 0);

I have no problems receiving the pointer and reading the values stored at that string. However if I were to do something similar like ...

struct msg_queue my_queue;
my_queue.message_type = 1;
my_queue.buffer = sum_buffer_with_lots_of_weird_values; // of type char *
msgsnd(mysqid, &pmb, sizeof(struct msg_queue) - sizeof(long), 0);

The pointer I pass through my queue to my other process will read garbage and not the values stored. I tried making my arbitrary array as a static char *, but that doesn't help either. How do I properly pass in my buffer through the queue? Thanks.

like image 757
Dr.Knowitall Avatar asked Jan 29 '26 18:01

Dr.Knowitall


1 Answers

You shouldn't be sending a pointers to another process, they have no meaning (or point to something very different) in another process' address space.

Message queues aren't great for unbounded data like variable length strings. Change your pointer to a fixed length char array sufficiently big to hold the largest string and copy your string into the array before writing the queue. Or use another type of IPC such as domain socket.

like image 160
Duck Avatar answered Feb 01 '26 09:02

Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!