4

In the code below I need num to be read from parent process and used within forked process child_proc(). But it doesn't see what's read in the parent process. What am I doing wrong?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int
is_prime(void);
void
child_proc(void);

int num = -1;

int
main(void)
{

    pid_t pid = fork();

    if (-1 == pid) {
        printf("Internal error\n");
        exit(1);
    }
    if (0 == pid) {
        printf("Starting child...\n");
        child_proc();
    } else {
        printf("Starting parent...\n");
        printf("Enter number to check:\n");
        scanf("%d", &num);  
        printf("You entered: %d\n", num);
    }
    sleep(1);
    if (pid == 0) {
        printf("Child Finished\n");
    } else {
        printf("Parent Finished\n");
    }
    return 0;
}

int
is_prime(void)
{
    int i;
    for (i = 2; i <= num; i++) {
        if ((num != i) && (num % i == 0)) {
            return 0;
            break;
        }
    }
    return 1;
}

void
child_proc(void)
{
    if (num <= 1) {
        printf("Incorrect value: %d\n", num);
    } else {
        int rc = is_prime();
        if (0 == rc) {
            printf("%d is not a prime\n", num);
        } else {
            printf("%d is a prime\n", num);
        } 
    }
}
JerzyJanowicz
  • 41
  • 1
  • 2

1 Answers1

4

After fork(2) the parent and the child become different processes and they don't share the same memory space. You need to use shared memory (see How to share memory between process fork()?) or maybe threads is better suited for you (https://computing.llnl.gov/tutorials/pthreads/).

Community
  • 1
  • 1