Search code examples
linuxbashprocesspid

Could last PID variable $! be wrong?


If a script launches a process and immediately after collects the PID with $!, could it get the wrong PID if somewhere else on the system a process is started in the moment between the time the script launches the process and when the script collects the PID with $!?


Solution

  • The $! special variable holds the PID of the last child process launched that the current shell started. It is never modified by actions happening in some other processes elsewhere on the system.

    $! can only be wrong if you yourself launch a new child process before collecting the value, because it's overwritten each time. For example, here the PID of "processX" is lost and the PID of "processY" is printed:

    processX &
    processY &
    
    echo Child process PID: $!