https://pages.cs.wisc.edu/~remzi/OSTEP/cpu-api.pdf
Process API
fork()
- Duplicates the process
- New process begins from
fork()call, notmain - Processes have a unique identifier called
pidfork()returns child pid to parent and 0 to child.
- Show
p1.c
wait()
- Allows you to wait for a child.
- Can be used to synchronize
- Can be used to clean up.
- There are different versions of
wait(e.g., can wait on a specific process instead of waiting for any child to terminate) - The return value in the return from
main(or as a parameter toexit) is made available to the parent indirectly throughwait - Show
p2.c
exec()
- Runs a new program
- Specifically transforms the current program into a new program by replacing (most of) the memory and resetting the state.
- To launch a new program is two steps:
fork(), thenexec() - Why
- Why do we need
fork()at all? Why not justexec()? - Why do we need to do a
fork()thenexec? Why not just jump right toexecwhen desired?- It provides the ability to alter the new program’s environment
- Environment variables
- (Processes can set using
setenv(). Children inherit environment and pass it throughexec)
- (Processes can set using
stdin/stdout- This is what makes file redirection work.
- Several versions of exec. Three basic modifiers:
l: Provide arguments as a list. Uses varargs likeprintfdoes.v: Provide a pointer to an array (instead of a separate parameter for each argument)p: Use the path. (Otherwise you must specify an absolute path name)e: Provide a custom environment (rather than passing the current environment)