Bash wait for process start

时间秒杀一切 提交于 2019-12-12 07:15:21

问题


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 ???


回答1:


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



回答2:


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 ]



回答3:


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


来源:https://stackoverflow.com/questions/19326245/bash-wait-for-process-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!