Home > database >  System call how to make parent wait for child
System call how to make parent wait for child

Time:01-23

This is my code system call in C.

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

int n;
int i;
pid_t pid;
int time = 1000;
int sum = 0;

int main(void) {
    printf("n: ");
    scanf("%d", &n);
    pid = fork();
    
    if (pid < 0) {
        printf("Fork Failed");
        exit(-1);
    } else if (pid == 0) {
        //child
        for (i = 1; i <= n; i  ) {
            sum  = i;
        }
        printf("Sum of 1 to %d: %d\n", n, sum); // this is ok
    } else {
        // parent
        wait(&time);
        printf("Sum of 1 to %d: %d\n", n, sum); // this always return 0;
    }
    return 0;
}

I don't know why in parent's code block, the sum is always equal to 0. How to make parent wait for child or am I doing something wrong ?

CodePudding user response:

Waiting for the child works. However, your expectations are wrong.

Apparently you think that computations in the child process after the fork are visible in the parent process. They are not. The child is a new copy of the parent program at the time of fork. At that time, the parent's sum is 0 and stays that way.

There are several mechanisms to pass data from child to parent.

  • exit() status
  • files
  • shared memory
  • pipes
  • anything else I have missed

CodePudding user response:

The issue here is the variable sum is not shared by the parent & child process, after fork() call the child will have its own copy of the variable sum. Use shmget(),shmat() from POSIX api. Or use pthread which will share the same memory space for the newly created thread.

  •  Tags:  
  • Related