在这里,我试图使子进程从文本文件中找到质数,并通过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是有问题的,但是我无法找到它.我希望有经验的人能帮助我.