Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this C code do?

Tags:

c++

c

fork

I'm really new to C programming, although I have done quite a bit of other types of programming.

I was wondering if someone could explain to me why this program outputs 10.

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

int value = 10;

int main()
{
    pid_t pid;

    pid = fork();
    if(pid == 0){
    value += 10;
    }
    else if(pid > 0){
        wait(NULL);
        printf("parent: value = %d\n", value); //Line A
        exit(0);
    }
}

I know the output is "parent: value = 10". Anyone know why?

Thanks!

like image 332
kralco626 Avatar asked Nov 30 '22 05:11

kralco626


2 Answers

fork creates two processes (the "parent" and the "child"). Each process has a different value of pid in your example. The child process has a pid of 0. The parent process has a pid of the child's operating system pid (assigned by the OS.)

In your example, each process has it's own value in its memory. They do not share memory (like you think they should by your question.) If you change one process (the first part of the if) it will not be reflected in the second process (the second part of the if.)

Edit: Explained the value of pid.

like image 55
Starkey Avatar answered Dec 09 '22 10:12

Starkey


About fork() :

  • If fork() returns a negative value, the creation of a child process was unsuccessful.
  • If fork() returns a zero to the newly created child process.
  • If fork() returns a positive value, the process ID of the child process, to the parent.

So in you case it bound to return a number greater than 0 & thus the value will remain 10 & will be printed.

like image 25
loxxy Avatar answered Dec 09 '22 11:12

loxxy