How to create process in Linux


 In Linux, we use fork( ) to create a new process which is actually a copy of the calling process. The new process is a copy (the code after fork( ) function) of its parent  process. So if we do nothing about control flow, the child process will actually do the same thing the parent does.
Here we use the return value of fork( ) to distinguish the child and parent. In fact, the function fork( ) returns two values after it finishes. For the calling process (parent process), it returns the PID of child process in order that the calling process can manage it. However in child process, fork() will return 0. So by this, we can just use a "if(chpid)" to distinguish the twos and make them execute the different sequences.
Another very important thing is the fork only copy the code after the for( ) function. It does not care about the code above is except the definition part of variables.
#include <stdio.h>
#include <sched.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
    pid_t chpid;
    int fd, status, variable=9;
    char ch;
    fd=open("test.txt", O_RDONLY);
    chpid=fork();
    if(chpid!=0)
        wait(&status);
    else
    { /*Executed only by the child*/
        variable=42;
        close(fd);
        printf("The child has changed the variable to: %d\n", variable);
        printf("The child has also closed the file.\n");
        return(0);
    }
    printf("The variable is now: %d\n", variable);
    if(read(fd, &ch, 1)<0)
    {
        perror("READ failed");
        return(1);
    }
    printf("Read from the file: %s\n", &ch);
    return (0);
}
Above is common use case of fork( ). The wait( ) function is used by calling processes to wait for the state changes of their child processes, like resume, termination, restart and so on. For detail, please refer to reference [1].
References:
[1] wait - Linux man page, http://linux.die.net/man/2/wait

Comments

Popular posts from this blog

Basic understanding of TLS-PSK protocol

Differences between ASIC, ASSP and ASIP

Orthogonal instruction set