'POSIX Queue Message Using fork() function
I am trying to create 2 processes ( client and server) through the fork() function and using the POSIX message queue to exchange messages. When I compile the client and server separately I have no issues and I get the results that I want. However, when I try to combine both the client and the server in the main function I get an error and nothing compiles. I am not sure if it's even possible to use fork() and POSIX message queue together in the main function.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <mqueue.h>
#include <sys/stat.h>
#define MQ_NAME "/mq_cola_queue"
typedef struct {
char msg[80];
}Message;
__pid_t wait();
int main (int argc, char* argv []) {
int id = fork();
// parent process (server)
if (id == 0) {
struct mq_attr attributes = {
.mq_flags = 0,
.mq_maxmsg = 10,
.mq_curmsgs = 0,
.mq_msgsize = sizeof (Message)
};
printf("Hello from parent.\n");
wait(1);
mqd_t queue = mq_open(MQ_NAME, O_CREAT | O_RDONLY | O_NONBLOCK, S_IRUSR | S_IWUSR, &attributes);
Message msg;
mq_receive(queue, (char *)&msg , sizeof(msg), NULL);
mq_close(queue);
mq_unlink(MQ_NAME);
return EXIT_SUCCESS;
// child process (client)
} else {
struct mq_attr attributes = {
.mq_flags = 0,
.mq_maxmsg = 10,
.mq_curmsgs = 0,
.mq_msgsize = sizeof (Message)
};
printf("Hello from child.\n");
mqd_t queue = mq_open(MQ_NAME, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR, &attributes);
Message msg;
strcpy(msg.msg, "This is my first message.\n");
mq_send(queue, (char *)&msg, sizeof (msg), 1);
/* wait for input to end the program */
fprintf(stdout, "Press any key to finish\n");
getchar();
mq_close(queue);
mq_unlink(MQ_NAME);
return EXIT_SUCCESS;
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
