exec(*args) public

Replaces the current process by running the given external command, which can take one of the following forms:

exec(commandline)

command line string which is passed to the standard shell

exec(cmdname, arg1, …)

command name and one or more arguments (no shell)

exec([cmdname, argv0], arg1, …)

command name, argv[0] and zero or more arguments (no shell)

In the first form, the string is taken as a command line that is subject to shell expansion before being executed.

The standard shell always means “/bin/sh” on Unix-like systems, same as ENV[“RUBYSHELL”] (or ENV[“COMSPEC”] on Windows NT series), and similar.

If the string from the first form (exec(“command”)) follows these simple rules:

  • no meta characters

  • no shell reserved word and no special built-in

  • Ruby invokes the command directly without shell

You can force shell invocation by adding “;” to the string (because “;” is a meta character).

Note that this behavior is observable by pid obtained (return value of spawn() and IO#pid for IO.popen) is the pid of the invoked command, not shell.

In the second form (exec(“command1”, “arg1”, …)), the first is taken as a command name and the rest are passed as parameters to command with no shell expansion.

In the third form (exec([“command”, “argv0”], “arg1”, …)), starting a two-element array at the beginning of the command, the first element is the command to be executed, and the second argument is used as the argv[0] value, which may show up in process listings.

In order to execute the command, one of the exec(2) system calls are used, so the running command may inherit some of the environment of the original program (including open file descriptors).

This behavior is modified by the given env and options parameters. See ::spawn for details.

If the command fails to execute (typically Errno::ENOENT when it was not found) a SystemCallError exception is raised.

This method modifies process attributes according to given options before exec(2) system call. See ::spawn for more details about the given options.

The modified attributes may be retained when exec(2) system call fails.

For example, hard resource limits are not restorable.

Consider to create a child process using ::spawn or Kernel#system if this is not acceptable.

exec "echo *"       # echoes list of files in current directory
# never get here

exec "echo", "*"    # echoes an asterisk
# never get here
Show source
Register or log in to add new notes.