clinuxlinux-kernelmq

Linux Posix Message Queue


Here, I am trying to do that the child processes are going to find the prime numbers from the text file and send them to the parent process via Linux Posix MQ and the parent print them onto the console at the same time. I am 100% sure that the isPrime algorithm works properly and text files are also found as expected. However, this printf statement printf("%ld\n", number); never executes.

I would be grateful if you can help me, I am kinda new in both C and 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;
}

I guess there is problem that I try to use MQ, however I am unable to locate it. I hope someone experienced can help me.


Solution

  • It was because of that I was using an online compiler. It works as expected on an actual machine.