fork() & wait() system call

Usually I don't create anything new in this professional blog, I just have a copy in my space with my understanding by exploring internet.

Process is any running instance of a program, and program is an executable file. This is an one line definition of process and program.

fork() is a linux system call to create a new child process by duplicating the calling process(parent). Both process run in the separate memory spaces. After a successful fork, the entire virtual address space of the parent is replicated in the child.

Return Value

Returns twice on success once in the parent and once in the child.

-1    returned in the parent which indicates no child process is being created.
0     indicates child process is being executed.
> 0  indicates parent process is being executed.




The child process is created with single thread, and child will not acquire parent's memory locks.

#include <stdio.h>
#include <unistd.h>  //getpid, getppid, fork
#include <stdlib.h>  // EXIT_SUCCESS, EXIT_FAILURE

void child () 
{
    printf("%s(), my pid is %d, and my parent's pid is %d\n",
           __func__, getpid(), getppid());
    exit(EXIT_SUCCESS);
}

void parent(pid_t pid)
{
    printf("%s(), my pid is %d, and my parent's pid is %d\n",
           __func__, getpid(), getppid());
    exit(EXIT_SUCCESS);
}

int main()
{
    pid_t pid = 0;
    
    printf("In %s\n",__func__);
    switch(pid = fork()) {
        case -1:
            perror("fork failed");
            exit(EXIT_FAILURE);
            break;
        case 0:
            child();
            break;
        default:
            parent(pid);
            break;
    }
        
    return 0;
}

Output:
1
2
In main
parent(), my pid is 4685, and my parent's pid is 4678

In the above program, parent process ()4685 doesn't wait til the child process executes, so we need to use wait() system call.

#include <stdio.h>
#include <unistd.h>  //getpid, getppid, fork
#include <stdlib.h>  // EXIT_SUCCESS, EXIT_FAILURE

void child () 
{
    printf("%s(), my pid is %d, and my parent's pid is %d\n",
           __func__, getpid(), getppid());
    exit(EXIT_SUCCESS);
}

void parent(pid_t pid)
{
    printf("%s(), my pid is %d, and my parent's pid is %d\n",
           __func__, getpid(), getppid());
    exit(EXIT_SUCCESS);
}

int main()
{
    pid_t pid = 0;
    
    printf("In %s\n",__func__);
    switch(pid = fork()) {
        case -1:
            perror("fork failed");
            exit(EXIT_FAILURE);
            break;
        case 0:
            child();
            break;
        default:
            wait(NULL);
            parent(pid);
            break;
    }
        
    return 0;
}

Output:
1
2
3
In main
child(), my pid is 28908, and my parent's pid is 28907
parent(), my pid is 28907, and my parent's pid is 28902


Sources
http://www.it.uu.se/education/course/homepage/os/vt18/module-2/process-management/



Comments