Exeptional Control Flow
- int fork(void)
- create a new process that is identical to the calling process.
- returns 0 to the child process.
- returns child’s pid(process id) to the parent process
pid_t pid = fork(); if(pid == 0) printf("hello from child\n"); else printf("hello from parent\n");
- Fork is called once but returns twice.
- atexit() registers functions to be executed upon exit
void cleanup(void){ printf("clean up\n"); } void fork6(){ atexit(cleanup); fork(); exit(0); }
- Reaping
- Performed by parent on zombie child(using wait and waitpid)
- Parent is given exit status information
- Kernel discards process
- What if parent doesn’t reap?
- if any parent terminates without reaping a child, then the child will be reaped by init process(pid == 1)
- so only explicit reaping in long-running processes
- ps command shows a list of zombies, in which the child process is marked as “defunct”.
- Killing parent(parents that you kill by the kill command.) allows child reaped by init, and the init function will reap it.
- In terms of killed parent(dead normally), you must kill the child by yourself.
- int wait(int *child_status): synchronizing with children
- Parent reaps child by calling the wait function
- int wait(int *child_status)
- suspends current process until one of its children terminates
- return value is the pid of the child process that terminated
- if child_status != NULL, then the object it points to will be set to a status indicating why the child process terminated
- waitpid(pid, &status, options):Waiting for a specific process
- suspends current process until specific process terminates
- various options
- int execve(char *filename, char *argv[], char *envp[])
- loads and runs in current process
- sigaction() is a much better way of handling signals.
- pause() is a function that suspends execution of the calling thread. The thread does not resume execution until a signal is delivered, executing a signal handler or ending the thread.