在这里,我试图使子进程从文本文件中找到质数,并通过Linux POSIX MQ将它们发送到父进程,父进程同时将它们打印到控制台上.我printf("%ld\n", number);%确定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;
}

我想我try 使用MQ是有问题的,但是我无法找到它.我希望有经验的人能帮助我.

推荐答案

这是因为我使用的是一个在线编译器.它在实际机器上的运行情况与预期一致.

C++相关问答推荐

你能用自己的地址声明一个C指针吗?

如何使用低级C++写出数值

LibpCap禁用监视器模式(C、MacOS)

函数内的局部字符指针

如何在C语言中正确打印图形

获取每个循环迭代结束时的当前时间

从TCP连接启动UDP(C套接字)

ifdef __cplusplus中的整数文字单引号

如何在GDB中查看MUSL的源代码

在C++中父进程和子进程中的TAILQ队列同步问题

获取前2个连续1比特的索引的有效方法

在函数外部使用内联ASM时无法指定操作数

不确定如何处理此编译错误

如何在C中用bool进行文件I/O?

用C++高效解析HTTP请求的方法

不带Malloc的链表

被调用方函数内部的C-Struct变量,它是指针还是无关紧要

try 判断长整数是否为素数

在C中,为什么这个带有递增整数的main函数从不因溢出而崩溃?

使用共享变量同步多线程 C 中的函数