fork () function | system calls

closed account (Nwb4iNh0)
Here is fork function, (linux system call) I dont actually understand why it looks like this and
what is getpid, pid , if someone can help, kindly explain this code.
I hope you help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <stdio.h>
#include <stdlib.h> 
#include <unistd.h>
int main(int argc, char*argv[]) {
printf("hello world (pid:%d)\n", (int) getpid());
int rc = fork();
if (rc < 0) {
// fork failed
printf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) {
// child (new process)
printf("hello, I am child (pid:%d)\n", (int) getpid());
} else {
// parent goes down this path (main)
printf("hello, I am parent of %d (pid:%d)\n",
rc, (int) getpid());
}
return 0;
}
Last edited on
this is C, is why it looks like that.
pid is "process identifier" which on most operating systems is simply an unsigned integer that the OS uses to keep track of running programs. You can get the value from the OS, which is useful to kill rogue processes or do other system administration type things like logging a process or user or tracking what programs use all your memory/CPU etc.

is there a specific thing you didn't understand, or is it just the general gibberish of the thing?
It looks like a toy / how-to / learning program but given the topic, they expected you to know C reasonably well (forking isnt something you do right away, you are expected to know the language reasonably well before getting here). Because of that they played fast and loose with some of the style.

there should be documentation on the PID stuff, which is likely in the unix std header that the program caught somewhere. That header is like windows.h ... its full of OS specific crap that is not really C++ but extensions to it for the OS in question.
Last edited on
Forking isn't too hard, but you need to read the man page through a few times, and play close attention to the return value.

On Windows you call a kernel function to have the OS load+initialize+start another process. The OS is kind of like a mental patient managing all his marbles. ;-)

On *nixen it works differently. There is no function to start a new process. Rather, you clone (or "fork") yourself, so that you have two identical processes running. The only difference between the two is the value returned from the fork() function. (You can dink some other differences too, but dont worry about that now.)

Once you have forked/cloned yourself, one of you replaces yourself with another image (from disk).

*there are several forking functions, including one called "clone", but fork() is the one that does all the work; the others are for special purposes.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.