2015-09-22 147 views
0

在下面的代碼中,我需要從父進程讀取num並在分叉進程child_proc()內使用。但是它沒有看到父進程中讀到的內容。我究竟做錯了什麼?在C中的fork()之後在進程之間共享數據

#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); 
     } 
    } 
} 

回答