user6111140
user6111140

Reputation:

parent process does not wait for the child process (c code)

char array[ARRAY_SIZE];

void child_process_routine(){
int j;
    for(j = 0;j<ARRAY_SIZE;j++)
    array[j]='d';
}

main()
{
    pid_t child_pid;
    int i;
    for(i = 0;i<ARRAY_SIZE;i++)
    array[i]='c';
    child_pid = fork();

        switch (child_pid) {
        case -1:
            perror("error");    
            exit(1);
        case 0: 
            child_process_routine();
            exit(0);    
        default:
            wait(NULL);
        }

    print_array(array); 
}

can you explain me why the parent process does not wait for the child process and this gives me the output " cccccc " again? it was changed in the child process into " dddddd "

what does wait(NULL) even do?

how does it supposed to know it should wait for the child process?

Upvotes: 0

Views: 2270

Answers (2)

Mukesh
Mukesh

Reputation: 83

fork() creates a different process but parent share the same process context.

but if you try to change anything in the stack segment of parent it makes a copy of that and creates a separate stack for child process, but all the resources like data segment, code segment, etc are not copied for child process. They both share it.

This copying on changing the data after fork is called "copy on write"

Parent process is waiting for child process to finish. But its printig for both parent and child separately and different data for both

Upvotes: 0

T Johnson
T Johnson

Reputation: 824

The parent process is waiting for the child process.

The child is not a thread, it is a completely different process with its own unique PID and the parent as its Parent PID. The child and the parent do not share the same array, the child has its own copy since it is a different process (not a thread of the same process). So when you set the array to 'd' in the child it does not affect the array in the parent process.

Try putting a sleep(20) in the child process flow right before it exits, and a printf() just before the parent wait(). You will see that your application pauses as the parent is waiting for the child to finish.

Upvotes: 1

Related Questions