Search code examples
pythonunixcronraspberry-pips

ps aux | grep x returns two root instances


I have a python script that starts on reboot using cron @reboot. When I use ps aux | grep x.py it returns two root instances and one user (in this case the user is pi) instance.

Is this a problem? How do I make sure there's only one instance?

Example: root 2317 0.0 0.3 4584 1484 pts/0 S+ 0.00 sudo python /home/pi/Twitter.py root 2318 36.5 3. 7 52072 16952 pts/0 S1+ 4.26 python /home/pi/Twitter.py


Solution

  • The reason you get two instances is because the grep sees both the x.py and the grep x.py processes.

    The best way to do this is to use pgrep x.py or you can use the trick of making your grep expression not match itself such as ps -aux | grep [x].py.

    WRT your followup comments: What happens when you run sudo, is that it creates another process. ps shows this process and sudo because they both have the string you are searching for in their argument list.

    If you look at the output of ps you should see something like this:

    0 62379   445   0  9:48pm ttys003    0:00.02 sudo x.py
    0 62383 62379   0  9:48pm ttys003    0:00.01 x.py
    

    Notice that the sudo has a process id of 62379 and x.py has a parent process id of 62379 which tells you it was started by sudo. The sudo process just sits there waiting for its child process to complete. It doesn't have any significant impact on the performance of your computer.

    I guess there are probably a few ways you can exclude the sudo process from your list. The easiest one I can think of is:

    ps -eaf | grep [x].py | grep -v sudo