In POSIX shells, which special variable expands to the process ID (PID) of the most recently executed background job?

Difficulty: Easy

Correct Answer: $!

Explanation:


Introduction / Context:
Scripting often requires capturing the PID of a background task to wait on it, send signals, or monitor its status. POSIX shells expose special parameters for this purpose, enabling robust job control and automation patterns without resorting to parsing ps output.


Given Data / Assumptions:

  • Shell: sh/bash/ksh/zsh with POSIX semantics.
  • A background job was started using command &.
  • We need the variable that holds that job's PID.


Concept / Approach:

$! expands to the PID of the most recently executed background pipeline. Other parameters have different meanings: $# is the number of positional parameters, $0 is the script's name, and $ expands positional parameters as a single word. Thus, $! is the correct way to capture and reference a background job's process ID immediately after launching it.


Step-by-Step Solution:

Start a job in background: sleep 60 &Immediately capture its PID: pid=$!Use PID as needed: wait "$pid" or kill "$pid".Confirm behavior by echoing $! right after &.


Verification / Alternative check:

Test snippet: ( sleep 3 ) & echo $! prints the PID, demonstrating the variable's semantics in interactive and script contexts.


Why Other Options Are Wrong:

  • $#: count of arguments to the script/function.
  • $0: name of the shell or script.
  • $*: all positional parameters; not a PID.
  • None of the above: incorrect because $! is standard.


Common Pitfalls:

  • Referencing $! too late; another background job might overwrite it.
  • Confusing $! with job control %1 notation used by the shell built-ins.


Final Answer:

$!.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion