Jump to content

fork system call analyze program without compiler for competitive exam guidance needed


Go to solution Solved by requinix,

Recommended Posts

  • Solution

Technically it depends on the language.

In general, though, the expectation is that the child process is a copy of the parent. Meaning the child's `a` will be a copy of the parent's. So they're not the same variable.

  • Like 1

Quick additional comment.  The result of fork is a new process, which I'm sure is clear.

What you might be missing is that the child process is identical to the parent at the moment of the fork call.

At that point you now have 2 identical processes that are proceeding from the point of the fork call, because they share the same call stack. 

 I converted your pseudo code into a small c program and compiled on my mac.  As the windows OS doesn't have fork and in general is entirely different this code would have to be compiled and run in WSL or a VM under windows

 

#include <stdio.h>
#include <unistd.h> // For fork

int main() {
    int a = 50;

    if (fork() == 0) {
        a += 5;     
    } else {
        a -= 5;
    }
    printf("Value of a: %d\n", a);
    return 0;
}

 

 

compile it and run: 

clang fork.c -o fork
./fork

Output:

Value of a: 45
Value of a: 55

At least under osx, it seems that the child process runs and exits first, although the underlying management of memory is left to the OS. 

It is likely that child processes will run first, because of the way memory is handled by the OS.  Fork wants to copy the memory space of the parent to the child, but the OS wants to defer that and uses "Copy on Write".  If it ends up being a situation where nothing in the child process differs, the OS doesn't need to copy memory, so the OS will likely opt to have the child process run before the parent process, but there's no strict rule or definition or relationship with fork, that requires one process to run before the other.  

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.