Sunday 23 October 2016

Understanding Exec

At times, you have noticed that there is a usage of exec in shell scripts. What it actually does, and where to use it exactly?

The command works on the theory of, is "never coming back"


exec command is shell builtin, and other members of the commands are execve, execvp, execv.

1. exec command starts the new process, without forking, so once it starts the new process, the old process get finished.

Case 1:
bash:~$ ps -ef | grep -i bash
csblog  13062 12371  1 15:19 pts/5    00:00:00 bash
ksh$ ksh
ksh$ ps -ef | grep -i ksh
csblog  13093 13062  0 15:19 pts/5    00:00:00 ksh
ksh$ ps -ef | grep -i bash
csblog  13062 12371  0 15:19 pts/5    00:00:00 bash

Case 2:
bash:~$ exec ksh
ksh$ ps -ef | grep -i bash
ksh$ ps -ef | grep -i ksh
csblog  13062 12371  0 15:19 pts/5    00:00:00 ksh

You can see, in case 1, i have started the process, without using exec, so the new shell, is subshell for the old one. But in case of case2, a totally new process is started. In this manner, your resources are saved.

2. Sometimes, you don't need user to access the shell, you can directly change in /etc/passwd, but you need to load the environment, so you can add the exec command, at the end of .profile.
3. exec, also used with file descriptor. To open, close, read and write.

exec 3< thisfile          # open "thisfile" for reading on file descriptor 3
exec 4> thatfile          # open "thatfile" for writing on file descriptor 4
exec 8<> tother           # open "tother" for reading and writing on fd 8
exec 6>> other            # open "other" for appending on file descriptor 6
exec 5<&0                 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4                 # copy write file descriptor 4 onto 7
exec 3<&-                 # close the read file descriptor 3
exec 6>&-                 # close the write file descriptor 6

read <&3
echo stuff >&4

Source: Stackoverflow.com

No comments:

Post a Comment