exec

  • english
  • spanish

exec is a built-in shell command that forces a binary to be executed by the currently running shell process instead of forking the process and running the binary on that child process.

When you run a command on a shell-script, it forks a child process and runs the command there. On a syscall level this is the classic:

if( (pid=fork()) == 0) { exec(command); exit(); } wait();

And this is usually what we want, because we will keep running commands after that one. Nevertheless, sometimes this is a problem, like when:

  • we have a program that’s going to monitor a given process, and it doesn’t run properly if there’s an intermediate shell process but we need to run this second process via a shel-script for whatever reasons (to initialize some variables, run the program with nice, whatever)
  • on MacOS we’re running a program via a shell-script and get two icons on the dock, one for the shell and another one for the program

Running a command with exec forces the shell not to fork, but to run the command directly over the shell process. An important thing to note here is that the shell-script will end there, no further commands of the shell script will be executed as the shell process will be substituted by the command process, so to speak.

#!/bin/sh # initialize variables, parse command-line parameters, etc. export IP=$1 exec nice command $*
Enviar a:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • BarraPunto
  • Meneame
  • Slashdot
  • Technorati
  • YahooMyWeb

Artículos relacionados (o no):

2 Responses to “exec”


  1. 1 Antonio

    Pues no lo pillo bien, me encontraba la semana pasada necesitando usar algo de exec y fork en perl, pero no lo pillo…

    P.D: Felicidades por el blog.

    saludos

  2. 2 bisente

    Probablemente no tenga nada que ver, lo que comento aquí es shell-script de línea de comandos (bash para entendernos) y lo que comentaba de llamadas al sistema C. Supongo que en perl será más similar al C que al bash pero nunca me ha hecho falta meterme a ese nivel en perl.

Leave a Reply




Creative Commons Attribution-NonCommercial 2.5 Spain
Creative Commons Attribution-NonCommercial 2.5 Spain