简体   繁体   中英

Shared memory between process prime number returning zero at child process

I'm studying concepts of processes and memory sharing between processes. so I took an example code and I'm trying to adapt it to calculate if a number is prime by memory sharing. The code compiles and correctly returns whether a number is prime or not. however I noticed that in case the number is Primo, instead of printing the number is always coming to zero. where am i going wrong in memory sharing?

thank you very much for the support

#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/shm.h>

int main(){
    
    int i, j;
    int prime;
    int count = 0;
    int *n;
    int shmid;
    int pid;
    
    
        printf("Enter a number:");
        scanf("%d", &prime);
    
    if(prime < 0){
        printf("Not a prime number!");
    }
    else if(prime == 0){
        printf("Not a prime number!");
    }
    else{
        shmid = shmget(5, 2*sizeof(float), IPC_CREAT | 0600 );
        
        n = shmat(shmid, 0, 0);

        pid = fork();
        if(pid > 0){
            count = 0;
            for(j = 2; j < prime; j++){
                if(prime % j == 0){
                    n[0] = prime;
                    count++;
                    wait(NULL);
                }
            }
            if(count == 0){
                printf("%d Is a prime number!\n", n[0]);
                shmdt(n);
            }   
            else{
                printf("%d Not a prime number!\n", n[0]);
                shmdt(n);
            }
        }
    }
}

You only write to the shared memory in the event that a number is not prime

if(prime % j == 0){
    n[0] = prime;

when count is incremented (possibly repeatedly).

Place n[0] = prime somewhere outside the loop, so both branches that test count can access the integer via the shared memory.

Or just print prime directly, seeing as both the shared memory and fork serve no practical purpose in this program. The child process does nothing except immediately exit. The shared memory is just a copy of existing data.

Note, you are allocating 2 * sizeof (float) for a single int .

Do not forget to remove shared memory segments from the system with shmctl , and check the return values of all shm* functions for failure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM