How exactly does fork() work?
The following code
#include <stdio.h>
int main (int argc, char const *argv[])
{
printf("Hi\n");
int i;
for(i = 1; i < argc; i++)
{
printf("Argument %d is %s\n", i, argv[i]);
fork();
printf("Forked in for loop increment %d\n", i);
}
return 0;
}
gives the following output
/a.out hello world
Argument 1 is hello
Forked in for loop increment 1
Argument 2 is world
Forked in for loop increment 2
Forked in for loop increment 1
Argument 2 is world
Forked in for loop increment 2
Forked in for loop increment 2
What code does fork execute first, in general. I would like to know the principles of fork() rather than based on just this one example. I could have had multiple arguments on the command line.
fork
is a system call, i.e. a library routine that calls into the kernel. When servicing a fork
call, the kernel creates a new process that executes the same program as the process that called it. The new process starts executing as if it had called fork
; the return value is different from the one in the parent, so you can distinguish the two.
The common idiom for invoking fork
is:
pid_t pid = fork();
switch (pid) {
case -1:
/* an error occurred, i.e. no child process created */
handle_error();
case 0:
/* a return value of 0 means we're in the child process */
do_child_stuff();
break; // or _exit()
default:
/* we're in the parent; pid is the child's process id */
do_parent_stuff();
}
How this works is: the OS makes a near-perfect copy of the process calling fork
(the PID and some other values are different, but the memory contents start out practically the same and usually the same files are opened in both). The copy is commonly done using so-called copy-on-write (COW) semantics, so there's hardly any actual copying done until one of the processes starts assigning to variables.
Be aware that number of process will grow exponentially, so for 100 arguments we are talking about 1267650600228229401496703205376 processes. I hope you have a really strong PC :).
I will answer your comment here, it will maybe help you to understand the fork.
After each loop you will double the number of process. So after N loops you will end up with 2^N process. Or after 100 loops you will end up with that big number I gave you.
Btw, fork bombs are one of the most common DoS attacks around :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With