Linux/Unix command to determine if process is running?

后端 未结 14 920
忘掉有多难
忘掉有多难 2020-11-28 01:54

I need a platform independent (Linux/Unix|OSX) shell/bash command that will determine if a specific process is running. e.g. mysqld, httpd... What

相关标签:
14条回答
  • 2020-11-28 02:36

    Putting the various suggestions together, the cleanest version I was able to come up with (without unreliable grep which triggers parts of words) is:

    kill -0 $(pidof mysql) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
    

    kill -0 doesn't kill the process but checks if it exists and then returns true, if you don't have pidof on your system, store the pid when you launch the process:

    $ mysql &
    $ echo $! > pid_stored
    

    then in the script:

    kill -0 $(cat pid_stored) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
    
    0 讨论(0)
  • 2020-11-28 02:42

    This approach can be used in case commands 'ps', 'pidof' and rest are not available. I personally use procfs very frequently in my tools/scripts/programs.

       egrep -m1  "mysqld$|httpd$" /proc/[0-9]*/status | cut -d'/' -f3
    

    Little explanation what is going on:

    1. -m1 - stop process on first match
    2. "mysqld$|httpd$" - grep will match lines which ended on mysqld OR httpd
    3. /proc/[0-9]* - bash will match line which started with any number
    4. cut - just split the output by delimiter '/' and extract field 3
    0 讨论(0)
提交回复
热议问题