inukaze
inukaze

Reputation: 439

Bash wait for process start

I'm trying to say to Bash , wait for a Process Start / Begin. I'm trying by this way for example:

notepad=`pidof notepad.exe`
    until [ $notepad > 0 ]
        do
            taskset -p 03 $notepad
            renice -n 5 -p $notepad
            sleep 5
            renice -n 0 -p $notepad
        done

well i have the follow questions:

  1. why this generate a file called “0″ (the file are empty) i dont wanna make a new file , just wait for the PID to check execution.

  2. This is a Loop , but if the 2 commands are execute correclty , 1 time how i can continue to done ???

  3. For this its better use "until or while" ???

  4. Another ideas for wait Process Start or Begin ???

Upvotes: 11

Views: 31314

Answers (3)

dwanderson
dwanderson

Reputation: 2832

To answer your first question: '>' is not the mathematical/comparison operator 'greater than'; it's bash's way of letting you pipe output to a file (handle).

echo "some text" > myfile.txt

will create a file named myfile.txt, and '>' sent the output of the command into that file. I would imagine that your file '0' has the pid in it, and nothing else.

Instead, try -gt (or related variants: -ge, -lt, -le, -eg, -ne) to test if one value is greater than (or: greater than or equal, less than, less than or equal, equal, not equal, respectively) to see if that helps. That is,

until [ $notepad -gt 0 ]

Upvotes: 2

damienfrancois
damienfrancois

Reputation: 59120

If I understand correctly, you want to wait until notepad is launched. Then the pidof must be inside your loop.

while ! pidof notepad.exe >> /dev/null ;
do
sleep 1
done
notepad=$(pidof notepad.exe)
taskset -p 03 $notepad
renice -n 5 -p $notepad
sleep 5
renice -n 0 -p $notepad

Upvotes: 2

that other guy
that other guy

Reputation: 123470

There are multiple issues with your code:

  1. pidof doesn't print 0 or -1 if there's no process, so your logic is wrong
  2. pidof can return multiple pids if there are multiple processes, which would break your comparison
  3. > has to be escaped in [ ] otherwise your code is equivalent to [ $notepad ] > 0, directing to a file.
  4. > isn't even the right operator. You wanted -gt, but as mentioned in point #1 and #2, you shouldn't compare numbers.
  5. until runs the loop until the condition is true. it doesn't wait for the condition to become true, and then run the loop.

This is how you should do it:

# Wait for notepad to start
until pids=$(pidof notepad)
do   
    sleep 1
done

# Notepad has now started.

# There could be multiple notepad processes, so loop over the pids
for pid in $pids
do        
    taskset -p 03 $pid
    renice -n 5 -p $pid
    sleep 5
    renice -n 0 -p $pid
done

# The notepad process(es) have now been handled

Upvotes: 26

Related Questions