Ask Your Question

How can a two-way communication be implemented using message queue in C?

asked 2021-10-30 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-02-02 21:00:00 +0000

lalupa gravatar image

A two-way communication using message queue in C can be implemented as follows:

  1. Create two message queues, one for sending messages from Sender to Receiver and another for sending messages from Receiver to Sender.
int mq_sender_to_receiver = mq_open("/sender_to_receiver", O_CREAT | O_RDWR, 0666, NULL);
int mq_receiver_to_sender = mq_open("/receiver_to_sender", O_CREAT | O_RDWR, 0666, NULL);
  1. Fork a child process, which will act as the Sender and the parent process will act as the Receiver.
pid_t pid = fork();
  1. In the child process (Sender), use mq_send() to send a message to the Receiver.
char msg[100] = "Hello, Receiver!";
mq_send(mq_sender_to_receiver, msg, 100, 0);
  1. In the parent process (Receiver), use mq_receive() to receive the message from the Sender.
char msg[100];
mq_receive(mq_sender_to_receiver, msg, 100, NULL);
  1. In the parent process (Receiver), use mq_send() to send a message to the Sender.
char response[100] = "Hello, Sender!";
mq_send(mq_receiver_to_sender, response, 100, 0);
  1. In the child process (Sender), use mq_receive() to receive the message from the Receiver.
char response[100];
mq_receive(mq_receiver_to_sender, response, 100, NULL);
  1. Print the messages received by both processes.
if (pid == 0) {
    // Sender process
    printf("Sender received: %s\n", response);
} else {
    // Receiver process
    printf("Receiver received: %s\n", msg);
  1. Finally, close and unlink the message queues. ``` mqclose(mqsendertoreceiver); mqclose(mqreceivertosender); mqunlink("/sendertoreceiver"); mqunlink("/receivertosender");
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2021-10-30 11:00:00 +0000

Seen: 18 times

Last updated: Feb 02 '22