简体   繁体   中英

messenger using message queue and multi thread in single program

I am trying to write a messenger program in Linux using message queue and pthread.

The program I have written parse the command line arguments to get the ids of the message queues like

user1) ./msg 4321 1234 // snd_key: 4321, rcv_key: 1234 

user2) ./msg 1234 4321 // snd_key: 1234, rcv_key: 4321

and then it creates two message queues: one to send, and the other to receive messages. Then it launches a thread to run sender() passing in &snd_queue as argument and receiver similarly. Then I have finished the program by Waiting for the two child threads using pthread_joing and then deallocated the two message queues.

The problem is that I cannot see the incoming messages by using two terminals. ( I can only see the message that I type) Also, on writing "quit" (which is supposed to end the program), it gives segmentation fault (core dumped).

I cannot understand what is the error in my program ( It does not have any compile errors)

pthread_create(&thread_send, NULL, sender(&snd_queue), NULL);
pthread_create(&thread_recv, NULL, receiver(&rcv_queue), NULL);

Both these lines are invalid. The first line is executing the function sender and then after it exits, you are creating the thread with the function that is it's return value. Because the return value of sender is return 0; , you are returning NULL , so I hope pthread_create fails with EINVAL . You want to pass the function pointer for thread creation and also you want toshould check the return value.

// error() is a GNU extension from `#include <error.h>

int err = pthread_create(&thread_send, NULL, sender, &snd_queue);
if (err) { error(-1, err, "pthread_create sender failed"); }

err = pthread_create(&thread_recv, NULL, receiver, &rcv_queue);
if (err) { error(-1, err, "pthread_create receiver failed"); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM