'What's the effect of combining exec and & in shell script?

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.


update:

The script is:

exec /mnt/usr/bin/pppd $DIAL_DEV unit $count call $PROVIDER ipparam $PROVIDER &

and at sometime:

# Shutdown ppp connection.
pppOff() {
  # Get device index.
  local index=$1  
  
  # Check connection.
  pppCheck $index
  if [ $? -ne 0 ]; then
    echo "invalid pppd: "$index
    return 1
  fi
  
  # Get pid.
  local PID=$PPPD_PID
  echo "pppd pid for "$index": "$PID
  
  # Kill
  kill -TERM ${PID}
  
  return 0
}

after executing the pppOff, the script itself is killed. So pppd is executed as the same process as the script maybe.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1