c - 为什么数组不能通过使用 fork() 函数来工作?

标签 c process fork

我尝试解决这个问题。

问题是

我应该创建一个创建子进程的进程。

子进程应将 1 到 10 写入大小为 10 的 int 数组 {初始值为0}。

母进程应该等到子进程写完。 子进程完成后,母进程打印出数组(例如 1,2,...,10)并将所有替换为 -1 并再次打印出数组。

child 是生产者,母亲是消费者。 (只有一个 child 和只有一个消费者。他们只这样做一次。)

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

int main(){
int arr[10]={0,};
pid_t pid;
int state;
pid = fork();

if(pid == -1) // error
{
    printf("can't fork, error\n");
    exit(-1);
}

else if (pid == 0) // Child ( producer )
{
    printf("\nProducer is created.\n");

    printf("array: ");
    for(c=0; c<10; c++)
    {
        printf("%d ", arr[c]);
        arr[c]=c+1;
    }

}

else // Mother ( consumer )
{
    pid=wait(&state);
    sleep(1);
    printf("\nConsumer takes control of array");


    printf("\narray:");

    for(j=0;j<10;j++) 
    {
        printf(" %d", arr[j]);
    }


    printf("\nConsumer is done.");

    printf("\narray: ");
    for ( i =0; i<10; i++)
    {

        arr[i]=-1;
        printf("%d ", arr[i]);


    }
    printf("\ndone\n");
    exit(0);
}
return 0;}

我要输出

0 0 0 0 0 0 0 0 0 0

1 2 3 4 5 6 7 8 9 10

-1 -1 -1 -1 -1 -1 -1 -1 -1 -1

但是

我的输出是

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0

-1 -1 -1 -1 -1 -1 -1 -1 -1 -1

我的代码有什么问题?

最佳答案

进程的内存地址空间将“写入时复制”。所以数组不在两个进程之间共享。

关于c - 为什么数组不能通过使用 fork() 函数来工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43673743/

相关文章:

c - 在 C 中对 char 数组进行操作的递归函数中的段错误

在C中编译多个文件

linux - 进程间读取不正确

c# - 从 tail -f "follow"捕获标准输出

java - 跳过从 PDF 读取的字节

c - Fork-exec 管道重定向问题

c - 通过 execlp 函数传递参数时出现问题 - C

c - 如何使用 C 中的 strtok 将 csv 中的后续列分配给数组

c - 当数组长度未知时,如何用用户输入值填充 C 中的数组

c - 在 fork 中写入和读取 - C