PDA

View Full Version : Passing function pointer using message queues



LxRz
05-05-2008, 08:04 AM
Hi

A general question first: is there a way to pass a function pointer between two user
space applications in Linux, using a message queue (msgsnd, msgget pair)?

Assuming that this can be done, here is what I'm trying to do:
================================
In a header file I've defined:
================================


typedef struct msgbuf{
int mtype;
int (*ptr)();
} message_buf;

int myfunc(int);

================================
In the sending application:
=================================


int myfunc(int mdata){
/*Do something */
return 0;
};
.
.
.
struct msgbuf* m_msg; /* Structure used for received messages. */
int queue_id; /* ID of the created queue. */
int i;

/* Access the public message queue. */
queue_id = msgget(QUEUE_ID, 0);
if (queue_id == -1) {
perror("msgget");
exit(1);
}

/* Allocate space for message */
m_msg = (struct msgbuf*)malloc(sizeof(struct msgbuf)+MAX_MSG_SIZE);

/* Set valid message type. */
m_msg->mtype = VALID_TYPE;

/* Set function. *** HOPING THIS IS RIGHT ***/
m_msg->ptr = myfunc;

/* Send message */
i = msgsnd(queue_id, m_msg, sizeof(struct msgbuf)+1, 0);
if (rc == -1) {
perror("msgsnd");
exit(1);
}

/* Free allocated memory. */
free(m_msg);
.
.
.

================================
In the receiving application:
=================================


struct msgbuf * m_msg; /* Structure used for messages. */
int i;
int (*func)(int);
.
.

while (1) {
i = msgrcv(m_qid, m_msg, MAX_MSG_SIZE+1, VALID_TYPE, 0);
if (rc == -1) {
perror("msgrcv");
exit(1);
}
func = m_msg->cb_ptr;
/*** HERE IS THE PROBLEM. SEGMENTATION FAULT WHEN REACHED ***/
i = func(100);
}
.
.


Any help, even more a sample code or link, is more than welcome.

LxRz

brewbuck
05-05-2008, 08:41 AM
In general a pointer from one process is meaningless in another. There is a chance, if both processes are running from the same binary, that a function pointer might work in both processes. But instead of counting on that, just pass a numeric code which indicates the function to be called, and dispatch the call with a switch statement or some other kind of lookup.

LxRz
05-05-2008, 10:34 AM
brewbuck thanx for the tip.

The method you described was my initial choice but what I'm really
after is passing a function pointer to realise a callback mechanism,
not in a local (same proccess) manner but between two applications
like this:
the first process delivers a message (including a callback pointer) to the
second, and when the second is done (asyhcronously) it replies using
the callback pointer.

Do you think this is possible? Thanx again.

LxRz

CornedBee
05-05-2008, 10:35 AM
No, that's absolutely impossible. The second process will have to send a message back.

LxRz
05-05-2008, 10:41 AM
CornedBee thanx for that ...
I'll implement a message queue to the reverse path as well, and let
the first process deal with the callback.

LxRz