What is exec?

As opposed to fork or other means that creates a new process, exec will replace the process that calls it.

Wikipedia:

In computing, exec is a functionality of an operating system that runs an executable file in the context of an already existing process, replacing the previous executable. This act is also referred to as an overlay. It is especially important in Unix-like systems, although exists elsewhere. As a new process is not created, the process identifier (PID) does not change, but the machine code, data, heap, and stack of the process are replaced by those of the new program.

exec is implemented in several programming languages. In Linux, we have an exec system call as well as a bash builtin.

type exec
exec is a shell builtin

Let’s do a simple example to understand what it means to replace the calling process.

The PID of my login shell is 5605.

[vagrant@localhost ~]$ ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
vagrant   5605  5604  0 17:29 pts/0    00:00:00 -bash
vagrant   5694  5605  0 17:40 pts/0    00:00:00 ps -f

I start a new shell by running “bash” and the PID of the new shell is 5695 which is a new process. Note that it’s PPID is my login shell 5605.

[vagrant@localhost ~]$ ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
vagrant   5605  5604  0 17:29 pts/0    00:00:00 -bash
vagrant   5695  5605  0 17:40 pts/0    00:00:00 bash
vagrant   5714  5695  0 17:41 pts/0    00:00:00 ps -f

If I exit, it returns to my login shell.

[vagrant@localhost ~]$ exit
exit
[vagrant@localhost ~]$ ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
vagrant   5605  5604  0 17:29 pts/0    00:00:00 -bash
vagrant   5716  5605  0 17:42 pts/0    00:00:00 ps -f

I am going to run “bash” again but this time with exec.

[vagrant@localhost ~]$ exec bash
[vagrant@localhost ~]$ ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
vagrant   5605  5604  0 17:29 pts/0    00:00:00 bash
vagrant   5735  5605  0 17:43 pts/0    00:00:00 ps -f

No new process is created. It retains the PID of my login shell 5605 When I exit, my ssh session is closed.

[vagrant@localhost ~]$ exit
exit
Connection to 127.0.0.1 closed.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s