← Back to Bash Course | Chapter 11: Process Management | Lesson 1 of 12

Background में Commands चलाना (&) और $!

किसी command के बाद एक ampersand जोड़ना Bash को बताता है कि उसे background में चलाना शुरू करे और बिना wait किए तुरंत next line पर move करे।
Syntax
bash
command &
process_id=$!
wait

Starting a Background Job

किसी command के बाद & लगाना इसे asynchronously launch करता है; shell इसके लिए wait नहीं करती और तुरंत next line पर continue करती है। यह independent tasks को concurrently run होने देता है।

उदाहरण: Starting a Background Job

bash
#!/bin/bash
sleep 0.2 &
echo "this prints immediately, before the sleep finishes"
wait
echo "the background sleep has now finished"

Capturing the Background PID with $!

$! सबसे recently शुरू हुए background job के process ID में expand होता है, जो एक script को बाद में उस specific process को track, wait, या signal भेजने देता है।

उदाहरण: Capturing the Background PID with $!

bash
#!/bin/bash
sleep 0.2 &
pid=$!
echo "started background job with PID $pid"
wait "$pid"
echo "job $pid has completed"

Running Several Jobs Concurrently

कई commands एक के बाद एक backgrounded हो सकते हैं; हर एक अपने शुरू होने के moment अपना अलग PID $! में रखता है, इसलिए अगर आप बाद में उन्हें individually reference करना चाहते हैं तो PIDs को separate variables (या एक array) में save किया जाना चाहिए।

उदाहरण: Running Several Jobs Concurrently

bash
#!/bin/bash
sleep 0.1 &
pid1=$!
sleep 0.1 &
pid2=$!
echo "started jobs $pid1 and $pid2"
wait "$pid1" "$pid2"
echo "both jobs finished"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि एक backgrounded command का output script के बाकी output के साथ interleave नहीं होगा; दोनों concurrently run होते हैं और overlapping times पर print कर सकते हैं।
  2. यह भूल जाना कि $! को & command के ठीक बाद capture किया जाना चाहिए, क्योंकि यह हमेशा सबसे recently backgrounded job के PID को refer करता है।
  3. Script खत्म होने से पहले background jobs के लिए wait न करना, जो एक interactive shell में ठीक है लेकिन एक non-interactive script के लिए इसका मतलब हो सकता है कि job का काम (जैसे एक file write) असल में पूरा होने से पहले ही script exit हो जाए।
चैप्टर सारांश
  • एक command के बाद & लगाना इसे background में शुरू करता है और तुरंत control वापस देता है।
  • $! सबसे recently शुरू हुए background job की process ID (PID) रखता है।
  • कई & jobs concurrently run हो सकते हैं; उनके खत्म होने तक block करने के लिए wait उपयोग करें।
  • Non-interactive scripts में job control disabled होता है, इसलिए fg/bg/jobs जैसे interactive builtins वहां unreliable हैं; $! और wait background work manage करने का portable तरीका हैं।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.