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

Process IDs और ps कमांड

System पर हर running program का एक unique number होता है जिसे process ID कहा जाता है, और ps command आपको यह list करने देती है कि कौन से programs run हो रहे हैं और उनके numbers क्या हैं।
Syntax
bash
echo "$$"       # current shell PID
echo "$!"       # last background job PID
ps -p process_id

The Current Shell's PID

$$ हमेशा script चला रहे current shell instance के process ID में expand होता है, जो unique temp filenames बनाने या यह log करने के लिए उपयोगी है कि किस process ने क्या किया।

उदाहरण: The Current Shell's PID

bash
#!/bin/bash
echo "this script's PID is $$"
tmpfile="/tmp/scratch_$$.txt"
echo "hello" > "$tmpfile"
cat "$tmpfile"
rm -f "$tmpfile"

Inspecting a Process with ps

ps -p PID -o field1,field2 एक specific process के लिए सिर्फ requested columns print करता है, जो scripts के लिए default, loosely formatted ps output को parse करने से कहीं ज़्यादा reliable है।

उदाहरण: Inspecting a Process with ps

bash
#!/bin/bash
ps -p $$ -o pid,ppid,comm

Checking a Background Job's PID

एक background job शुरू करने के बाद, $! (PID) और ps -p (यह confirm करने के लिए कि यह मौजूद है और इसे inspect करने के लिए) दोनों साथ उपयोग किए जा सकते हैं यह verify करने के लिए कि एक job उस पर wait करने से पहले असल में run हो रही है।

उदाहरण: Checking a Background Job's PID

bash
#!/bin/bash
sleep 0.3 &
pid=$!
if ps -p "$pid" > /dev/null; then
    echo "job $pid is running"
fi
wait "$pid"
if ! ps -p "$pid" > /dev/null 2>&1; then
    echo "job $pid has finished and is gone"
fi
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. यह मान लेना कि $$ एक background job के PID को refer करता है; $$ हमेशा CURRENT shell के अपने PID को refer करता है, किसी child process को नहीं।
  2. $$ (current shell PID) को $BASHPID के साथ confuse करना, जो एक subshell के अंदर असली subshell की PID reflect करता है, जबकि $$ कुछ contexts में अब भी original shell report करता है।
  3. ps output को fragile column-position assumptions से parse करना बजाय exactly जो fields चाहिए वे एक stable format में request करने के लिए ps -o उपयोग करने के।
चैप्टर सारांश
  • $$ current shell की अपनी process ID में expand होता है।
  • $! सबसे recently backgrounded job के PID में expand होता है, current shell के नहीं।
  • ps -p PID -o pid,ppid,cmd एक process के लिए specific fields एक predictable format में print करता है, scripting के लिए अच्छा।
  • बिना arguments के ps typically सिर्फ current terminal session से attached processes दिखाता है।

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.