The Fork Function Call
-
pid_t fork(void);
- Creates a new process with nearly every resource duplicated.
- Both processes return to the same point in execution.
- The child process gets a 0 as the return value.
- The parent process gets the Pid of the child process as a return value.
- A -1 is returned to the parent on error and no child is created.
- There are very few errors, mostly related to system resource limits.
- The man page lists the other differences in the child process
- parent process id is different.
- No memory locks are inherited
- CPU and other resource counters are set to 0
- Pending signals are emptied (Parent gets all signals)
- Several other very specialized things.
- Behavior for threaded programs is different.
- The order of execution of the two processes is non-deterministic.
- Sleep:
- Sleep is a system call that will put the program into a wait state.
-
unsigned int sleep(unsigned int seconds);
- If the return is 0, it slept as long as you wanted
- If the return is positive, something forced it to "wake up" early that many seconds.
- A sleep does not guarantee that one process will run before the other.
- I/O:
- This is actually the next section, but open file descriptors are shared.
- The terminal only waits for the parent process. (We should have seen this by now in zombie)
- It is not deterministic (ie a race condition) who reads or writes next.
- There are mechanisms to handle this, but we need the basics first.
- I generally label my output (parent and child) but there is no promise that full blocks will be written.
- BE VERY CAREFUL when forking multiple times.
- This can turn into a denial of service attack.
- Don't do this on cslab103.
- If you do, don't try to hide it.
- Let Preston, or I , or BOTH know as soon as you break something.
- I will try to get a server spun up for experimentation before you have code to write.
- Look at basicFork.cpp
- File Descriptors.
- As we should have seen in the above example, file descriptors are shared by the parent and child process.
- So the file offset is shared.
- Take a look at filePointer.cpp.
- RACE CONDITIONS can occur.
- Memory Semantics
- Fork does a copy on write.
- Ie, both processes point to the same memory until one tries to write.
-
- This is because fork is frequently followed by an
exec
which allocates new memory anyway.
- vfork
- Designed to be a fast for, which MUST be followed by an exec.
- The calling process is suspended until the child exits or calls exec.
- The child must call exec immediately ,as all memory, including the stack, is shared.
- This is really dangerous, and should only be used in situations where it is required.