【问题标题】:Sharing data between processes after fork() in C [duplicate]在C中的fork()之后在进程之间共享数据[重复]
【发布时间】:2015-12-19 16:08:49
【问题描述】:

在下面的代码中,我需要从父进程读取num 并在分叉进程child_proc() 中使用。但它看不到父进程中读取的内容。我做错了什么?

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

【问题讨论】:

    标签: c fork


    【解决方案1】:

    fork(2)之后,父子进程变成不同的进程,不共享相同的内存空间。您需要使用共享内存(请参阅How to share memory between process fork()?)或者线程可能更适合您(https://computing.llnl.gov/tutorials/pthreads/)。

    【讨论】:

      猜你喜欢
      • 2014-01-28
      • 2018-01-08
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 2021-06-15
      • 2012-03-19
      相关资源
      最近更新 更多