Linux Posix 消息队列

问题描述 投票:0回答:1

在这里,我试图让子进程从文本文件中查找素数,并通过 Linux Posix MQ 将它们发送到父进程,同时父进程将它们打印到控制台上。我 100% 确定 isPrime 算法正常工作,并且也按预期找到了文本文件。然而,这个 printf 语句

printf("%ld\n", number);
永远不会执行。

如果您能帮助我,我将不胜感激,我对 C 和 Linux 都很陌生。

int main() {
    struct mq_attr mq_attributes = {
      .mq_flags = 0,
      .mq_maxmsg = M,
      .mq_curmsgs = 0,
      .mq_msgsize = sizeof(int64_t)
    };

    mqd_t mq;
    mq = mq_open(MQ_NAME, O_CREAT | O_RDWR, 0644, &mq_attributes);

    for (int i = 0; i < N; i++) {
        pid_t pid = fork();

        if (pid < 0) {
            perror("Fork failed");
            exit(EXIT_FAILURE);
        } else if (pid == 0) {

            char fileName[26];
            sprintf(fileName, "inter_file_%d.txt", i);
            FILE *file = fopen(fileName, "r");
            if (file == NULL) {
                perror("Intermediate file open failed");
                exit(EXIT_FAILURE);
            }

            int64_t number;
            while (fscanf(file, "%ld", &number) == 1) {
                if (isPrime(number)) {
                    mq_send(mq, (void *) &number, sizeof(number), 0);
                }
            }

            remove(fileName); // Remove the intermediate file
            exit(EXIT_SUCCESS); // Child process terminates
        }
    }
  
    int64_t number;
    while (mq_getattr(mq, &mq_attributes) == 0) {
        if (mq_attributes.mq_curmsgs > 0) {
            for (int i = 0; i < mq_attributes.mq_curmsgs; i++) {
                mq_receive(mq, (void *) &number, sizeof(number), NULL);
                printf("%ld\n", number);
            }
        }
    }

    mq_close(mq);
    mq_unlink(MQ_NAME);

    return 0;
}

我想我尝试使用 MQ 时出现问题,但我无法找到它。希望有经验的人可以帮助我。

c linux linux-kernel mq
1个回答
0
投票

这是因为我使用的是在线编译器。它在实际机器上按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.