Fork () process

How does fork () work?

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 conclusion

/a.out hello world

Argument 1 welcomes

Filled to increment cycle 1

Argument 2 - The World

Filled to increment cycle 2

Filled to increment cycle 1

Argument 2 - The World

Filled to increment cycle 2

Filled to increment cycle 2

Which code executes fork first, in general. I would like to know the principles of fork (), not just this example. I could have several arguments on the command line.

+6
c fork
source share
2 answers

fork is a system call, that is, a library procedure that calls in the kernel. When servicing a fork call, the kernel creates a new process that runs the same program as the process it invoked. The new process starts as if it was calling fork ; the return value is different from the value in the parent, so you can distinguish between the two.

Common idiom for calling fork :

 pid_t pid = fork(); switch (pid) { case -1: /* an error occurred, ie 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 process id */ do_parent_stuff(); } 

How it works: The OS creates an almost perfect copy of the process that calls fork (PID and some other values ​​are different, but the contents of the memory start almost the same, and usually the same files open in both). Copying is usually performed using the so-called copy-on-write (COW) semantics, so there is practically no real copying until one of the processes begins to assign to variables.

+9
source share

Keep in mind that the number of processes will grow exponentially, so for 100 arguments we are talking about processes 1267650600228229401496703205376. I hope you have a really strong PC :).

I will answer your comment here, this will help you understand the plug.

After each cycle, you will double the number of processes. So, after N cycles, you get a 2 ^ N-process. Or after 100 cycles, you end up with the large amount that I gave you.

Btw, fork bombs are one of the most common DoS attacks :)

+3
source share

All Articles