>_ IzzyLab

Hands-on task

This task is step 17 of the course “Processes and signals”

Background jobs: wait and exit codes

medium~8 min

/opt/batch/ has three jobs: job1.sh, job2.sh, job3.sh — each runs for a couple of seconds and exits with its own code. Write a script /root/run-jobs.sh that starts all three in parallel in the background, waits for each via wait by its PID, and writes the return codes to /root/codes.txt — one per line, in the order job1, job2, job3. Make the script executable and run it. The jobs in /opt/batch/ change, so don't write the codes into the script: it must work with any jobs.

What you'll practise:
  • wait
  • background jobs
  • $!
  • $?
  • return codes

Topic breakdown

When a command is launched in the background via &, the shell doesn't block and keeps working, while the PID of the launched process is placed into $! — but this variable is overwritten on each new background launch, so the PID you need must be saved into a separate variable immediately. The built-in wait PID command waits for a specific process and, crucially, sets $? to its exit code. This lets you run several jobs in parallel and then collect their codes in order. Reminder: true exits with code 0, false with 1.

What's checked

  1. the /root/run-jobs.sh script exists and is executable
  2. the job codes are collected in /root/codes.txt
  3. the script works with other jobs too, running them in parallel

What it looks like