FORK() hard to understand
The fork() function is used to create a new process by duplicating the existing process from which it is called.
for example int main(void) { pid_t childPID; int var_lcl = 0; statement1 ; statement2 ; statement3 ; childPID = fork(); if(childPID >= 0) // fork was successful { if(childPID == 0) // child process { do child statements } else //Parent process { do parent statements } } else // fork failed { } My question is will statements 1 to 3 be executed in child without mentioning this just because they apear in the calling process ? Elico |
Execution in the child continues with the statement following the fork() call, just as does the parent. The child process does not restart from the beginning.
|
Thanks
Can you show me a simple example please ? Elico |
what kind of example do you need?
Code:
childPID = fork(); |
Initially there is one process, that executes statement1, statement2, statement3. When it comes to fork() the kernel make a copy of the process, and you have the original continuing the execution with fork returning the pid of the child, the child instead get a 0 from fork.
|
Thanks
Now in what cases the FORK() is used ? Also can the child send a message to the father ? Elico |
1. fork() (note lowercase) is used for multi-processing, as you are creating multiple processes from one program.
Typically it's used to parallel process a problem eg Apache has several different methods of working, one of which is fork()'ing. 2. Various methods can be used to send a msg back to the parent from the child, eg shared memory, temp files, sockets of various types (tcp, udp, Unix) However, these days, if you need to do a lot of data sharing back and forth, most people would use threads instead. This is easier, as you can declare a variable to be thread-global. |
Thanks
Elico |
Quote:
** The one exception is the init process (PID 1), which is the ultimate ancestor of every other process on the system. |
Thanks
Looks like a long way to grasp and master linux .. Elico |
All times are GMT -5. The time now is 06:29 PM. |