简体   繁体   中英

Why doesn't array work by using fork() function?

I try to solve the question.

Question is that

I should creat a process creating child process.

Child process should write 1 to 10 to the int array size of 10 { initial value of 0 }.

Mother process should wait until the child done writing. AFter the child process finishes, the mother process print out the array ( ex. 1,2,...,10) and replace all to -1 and print out the array one more time.

Child is a producer and Mother is a consumer. ( Only one child and Only one consumer. and they do this only once.)

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

I want output

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

but

my out put is

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

what's the problem with my code?

The memory address spaces of the processes will "copy on write". So the array is not shared between the two processes.

If you want to share substantial data between different processes (like parent and child), there are a number of ways. Three of the most common are

  1. Producer writes to a file; Consumer reads the file
  2. Shared Memory, as provided by the shm* API of the Unix kernel
  3. Memory mapped files, as provided by the mmap API of the Unix kernel

Suggestion: read everything you can find by the late great W. Richard Stevens, such as Programming in the Unix Environment .

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