Skip to content

Fork( ) and Execve( ) System Calls

sarahmss edited this page Dec 21, 2021 · 4 revisions

UNIX system calls are used to manage the file system, control processes, and to provide interprocess communication. The UNIX system interface consists of about 80 system calls (as UNIX evolves this number will increase).

  1. A system call is just a request for the operating system to do something on behalf of the user's program.
  2. The system calls are functions used in the kernel itself.
  3. The system call appears as a normal C function call. However since a system call executes code in the kernel, there must be a mechanism to change the mode of a process from user mode to kernel mode.
  4. The instruction that causes the mode change is often referred to as an "operating system trap" which is a software-generated interrupt.
  5. The kernel looks up the system call number in a table to find the address of the appropriate kernel routine that is the entry point for the system call and to find the number of parameters the system call expects.

To execute a command three system calls are made:

fork / execve / wait

Fork

Using the fork() system call, the shell clones itself into another process, with copies of its heap and stack states, as well as the runtime position. Saving the return value of fork() - [0:child process|!0:Parent process] we can obtain information about which process we're in. inside the parent, we can use the wait() to halt its running state until its child process terminates. Once this happens, the parent can take over and resume its next iteration inside the infinite loop. Sockets are the same for both processes When the process is forked, the environment is copied and passed to the new process. The shell will look for the program file that we are trying to execute where all the executable files are in the system in the $PATH variable, where we can find a list of directories containing the executable binary files.

Execve

  1. Loads a new program into a process's memory
  2. The existing process is discarded
  3. The newly create process gets an all-new stack, data & heap.
  4. Since it replaces the process's memory, the return value is always -1. execve(pathname, argv, envp)
  5. Pathname: the pathname of the command to execute
  6. argv: The arguments to pass to new program
  7. envp: the environment list

Clone this wiki locally