int fork()

— Basics —

Creates a process, returns child’s PID.

return values :

< 0 - error

0 - we’re in the parent process

== 0 - we’e in the child process

— Code —

int main() {
	if(fork()==0) {
		fprintf(1, "Hello from child.\n");
	} else {
		fprintf(1, "Hello from parent.\n");
	}
	exit(0);
}

— Theory —

A process may create a new process using the fork system call. fork gives the new process the exact copy of the calling’s process memory, intructions and data. In the original process fork returns the child PID. In the child process it returns 0. The original process is called parent and the new child.

fork copies the parent’s file descriptor table along with its memory, so that the child starts with exactly the same open files as the parent.


int exit(status)

— Basics —

Terminate the current process; status is reported to wait(). No return.

To clarify, the exit function is in kernel/proc. has a return type of void, in the declaration in user.h exit is declared with the return type int, but is set to not return anything.

status == 0 → success