简体   繁体   English

信使在单个程序中使用消息队列和多线程

[英]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.我正在尝试使用消息队列和 pthread 在 Linux 中编写一个信使程序。

The program I have written parse the command line arguments to get the ids of the message queues like我编写的程序解析命令行 arguments 以获取消息队列的 ID,例如

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.然后它启动一个线程来运行 sender() 传递 &snd_queue 作为参数和接收者类似。 Then I have finished the program by Waiting for the two child threads using pthread_joing and then deallocated the two message queues.然后我通过使用 pthread_joing 等待两个子线程完成了程序,然后释放了两个消息队列。

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.第一行正在执行 function sender ,然后在它退出后,您正在使用 function 创建线程,这是它的返回值。 Because the return value of sender is return 0;因为sender的返回值是return 0; , you are returning NULL , so I hope pthread_create fails with EINVAL . ,您将返回NULL ,所以我希望pthread_createEINVAL失败。 You want to pass the function pointer for thread creation and also you want toshould check the return value.您想通过 function 指针来创建线程,并且您还想检查返回值。

// 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"); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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