Background में Commands चलाना (&) और $!
In this page:
command &
process_id=$!
wait
Starting a Background Job
किसी command के बाद & लगाना इसे asynchronously launch करता है; shell इसके लिए wait नहीं करती और तुरंत next line पर continue करती है। यह independent tasks को concurrently run होने देता है।
उदाहरण: Starting a Background Job
#!/bin/bash
sleep 0.2 &
echo "this prints immediately, before the sleep finishes"
wait
echo "the background sleep has now finished"
Login to try C/C++/Java/PHP code in the editor
Capturing the Background PID with $!
$! सबसे recently शुरू हुए background job के process ID में expand होता है, जो एक script को बाद में उस specific process को track, wait, या signal भेजने देता है।
उदाहरण: Capturing the Background PID with $!
#!/bin/bash
sleep 0.2 &
pid=$!
echo "started background job with PID $pid"
wait "$pid"
echo "job $pid has completed"
Login to try C/C++/Java/PHP code in the editor
Running Several Jobs Concurrently
कई commands एक के बाद एक backgrounded हो सकते हैं; हर एक अपने शुरू होने के moment अपना अलग PID $! में रखता है, इसलिए अगर आप बाद में उन्हें individually reference करना चाहते हैं तो PIDs को separate variables (या एक array) में save किया जाना चाहिए।
उदाहरण: Running Several Jobs Concurrently
#!/bin/bash
sleep 0.1 &
pid1=$!
sleep 0.1 &
pid2=$!
echo "started jobs $pid1 and $pid2"
wait "$pid1" "$pid2"
echo "both jobs finished"
Login to try C/C++/Java/PHP code in the editor
- यह मान लेना कि एक backgrounded command का output script के बाकी output के साथ interleave नहीं होगा; दोनों concurrently run होते हैं और overlapping times पर print कर सकते हैं।
- यह भूल जाना कि
$!को&command के ठीक बाद capture किया जाना चाहिए, क्योंकि यह हमेशा सबसे recently backgrounded job के PID को refer करता है। - 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 हैं;$!औरwaitbackground work manage करने का portable तरीका हैं।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: