I maintained some legacy Linux shell script codes, and I met something like this:
#!/bin/sh
foo()
{
exec some_shell_command &
return 0
}
foo
I'm very curious about the effect of such shell scripts. Is some_shell_command executed in another subprocess? And after the execution of exec command, does shell script process become the some_shell_command process?
Thanks in advance.
CodePudding user response:
Is some_shell_command executed in another subprocess?
Yes.
after the execution of exec command, does shell script process become the some_shell_command process?
There are two processes, the one spawned for the background becomes some_shell_command
. Parent continues execution.
does it mean 'exec' is meaningless?
It has very little meaning in this specific context. Generally, you should expect that Bash optimizes and if Bash finds out there is only one command, it will optimize it to an exec
.
$ strace -ff bash -c '/bin/echo 1' 2>&1 | grep clone
# nothing, because `fork()` is optimized out
There are cases (see https://github.com/bminor/bash/blob/f3a35a2d601a55f337f8ca02a541f8c033682247/builtins/evalstring.c#L441 https://github.com/bminor/bash/blob/f3a35a2d601a55f337f8ca02a541f8c033682247/builtins/evalstring.c#L124 ) where the command is not optimized, mostly in the case of like trap
or some signal handling that Bash needs to execute after the command is done.
Another difference is that exec
requires specifically an executable, where without exec
then some_shell_command
could be a built-in, function or an alias.