Title: Basic process control system calls
1Basic process control system calls
- COMS W4118
- Henning Schulzrinne
2Process model for shell
shell (pid 10)
fork()
foreground (pid 12)
background (pid 14)
background (pid 15)
child
child
child
3Execute program
include ltunistd.hgt int execve(const char
filename, char const argv , char const
envp)
- Example execve(./a.out, argv, envp)
- Replaces existing code with program
- on success, does not return
- process exits instead
- on error, returns -1 (see errno)
4Forking
- fork creates a child process that differs from
the parent process only in its PID and PPID, and
in the fact that resource utilizations are set to
0. - Returns
- on success, PID of child is returned to parent
- 0 is returned to child
- on failure, return -1 (and errno)
if ((pid fork()) 0) / heres the child
/ exec() else / heres the parent /
wait for child(pid)
5Wait for child process
include ltsys/types.hgt include
ltsys/wait.hgt pid_t wait(int status) pid_t
waitpid(pid_t pid, int status, int options)
- Can either wait for process (synchronous)
- or poll (WNOHANG)
- use with SIGCHLD signal handler
- while ((c_pid waitpid()) gt 0)
- Returns process ID of process that exited
6I/O redirection - dup
include ltunistd.hgt int dup(int oldfd) int
dup2(int oldfd, int newfd)
- dup and dup2 create copies of a file descriptor
- both are the same
- dup2 makes newfd a copy of oldfd, closing newfd
first - I.e., operations on newfd are done on oldfd
instead - Send output to outfd instead of standard output
- dup2(outfd, STDOUT_FILENO)
- For shell, redirect I/O in child, then exec()
7Error handling
include ltstdio.hgt void perror(const char s)
- errno - integer
- perror() prints string followed by last error
message