【发布时间】:2020-12-08 19:59:49
【问题描述】:
我正在尝试使用 POSIX 消息队列将消息从子进程发送到父进程。在使用 fork() 创建子代之前,我创建了消息队列。我的代码应该从链接列表中获取单词并将它们发送给父级。但是,当我调用 mq_send 函数发送数据时,程序会卡在函数中,尝试从控制台获取输入并且永远不会停止。我已经在这个问题上工作了一天多,但我不知道该怎么做。我检查了代码的其他部分,它们都可以工作。只有 mq_send 函数会导致问题。有人可以告诉我这里有什么问题吗?也许我错过了一些东西。代码如下。
注意:我不能在此处包含所有代码。这里只有与问题相关的部分。另外,这是我在 stackoverflow 中的第一个问题,所以对于可能的格式错误,我深表歉意。
编辑:代码无法编译,因为我没有添加所有部分。我的问题仅基于发送消息的代码的最后一个 while 循环。这就是代码卡住的地方。
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <math.h>
#include <string.h>
#include <sys/types.h>
#include <mqueue.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
struct Node {
char value[1024];
int count;
struct Node* next;
};
struct dataPackage {
char word[1024];
int count;
};
int main(int argcount, char** argvalues) {
struct Node* headList[atoi(argvalues[1])]; // an array to hold linked lists
// creating fileCount number of linked lists and storing them
for ( int i = 0; i < atoi(argvalues[1]); i++ ) {
headList[i] = NULL;
}
// creating message queues
mqd_t mqList[fileCount];
char queueNames[5][1024];
int n;
// creating different names for different message queues
strcpy(queueNames[0], "/queue1");
strcpy(queueNames[1], "/queue2");
strcpy(queueNames[2], "/queue3");
strcpy(queueNames[3], "/queue4");
strcpy(queueNames[4], "/queue5");
// creating the message queues
for (int i = 0; i < atoi(argvalues[1]); i++ ) {
mqList[i] = mq_open(queueNames[i], O_RDWR | O_CREAT, 0666, NULL );
printf("%i\n", mqList[i]);
}
// creating child processes to process input files
for (int i = 0; i < atoi(argvalues[1]); i++ ) {
// creating a child process
pid_t pid = fork();
// child processes process seperate files
if (pid == 0 ) {
//printf("Before file process\n");
// processing the file and creating the sorted linked lists
processFile(fileNames[i], &headList[i]);
// send linked list contents to parent process below
struct dataPackage package;
struct Node* tempHead = headList[i];
while (tempHead != NULL) {
// creating a package to send it to the parent process
package.count = tempHead->count;
strcpy(package.word, tempHead->value);
// !!!!!this is the part where the program gets stuck!!!!!!!!
n = mq_send(mqList[i], (char*) &package, sizeof(struct dataPackage), 0);
tempHead = tempHead -> next;
}
// creating a message that will indicate the end of message queue
package.count = -10;
strcpy(package.word, "stop");
n = mq_send(mqList[i], (char *) &package, sizeof(struct dataPackage), 0);
exit(0);
}
else {
wait(NULL);
}
}
【问题讨论】:
-
char** argvaluesstruct Node* headList[argvalues[1]];大小为char*的数组?你认为那条线有什么作用?i < argvalues[1]int和char*之间的比较?你没有从你的编译器那里得到一堵警告墙吗?一定要修复它们。i < atoi(argvalues[1])哦?I cannot include all the code here为什么不呢?提供minimal reproducible example 可以更快地获得帮助。 -
您的代码没有按照提供的那样编译,因此很难确定可能是什么实际问题。您需要提供minimal reproducible example
-
@KamilCuk 我在复制代码时很着急。它实际上是 i
标签: c posix message-queue ubuntu-18.04