Skip to main content
 首页 » 编程设计

linux之Cron-Bash : How to babysit an app on linux

2026年04月21日51zengkefu

所以,我有一个在 Linux 上运行的应用程序。不幸的是,该应用程序并不像它需要的那样稳定。所以,我需要照顾它并确保它正常工作。我的应用程序立即 fork 出 6 个进程。我想出了一个可行的方案,但我想知道是否有更好的方法来实现这一点。因此,我的脚本每分钟由一个 cron 作业运行 1 次。我的脚本需要:

  1. 确保初始进程仍在运行。
  2. 确保列表中的 6 个分支正在运行。

这是我目前的脚本:

 #!/bin/sh 
 
 #myprocess -s will return the status of the running process 
 output=`myprocess -s`; 
 
if [ "$output" != "No myprocess found." ] ; then 
  myprocess_pid=`echo $output | cut -d":" -f2`; 
 
  #checks if that pid is running 
  myprocess_running=`ps | grep $myprocess_pid | grep myprocess`; 
 
  #if the string is an empty string, means script isn't running anymore. 
  if [ -z "$myprocess_running" ] ; then 
 
    #fires it off 
    echo "`date` - myprocess not running ...." >> /tmp/log/messages; 
    myprocess; 
 
  fi 
else #it ain't running 
 
   echo "`date` - output from myprocess -s: $output" >> /tmp/log/messages;       
   myprocess; 
 
fi 

如何改进?

感谢您的任何建议!

请您参考如下方法:

  1. myprocess -s可以设置一个返回码 != 0;你可以写

    if myprocess -s; then 
         ... code-when-ok ... 
    else 
         ... code-when-failure ... 
    fi 
    
  2. 当你有 pid 时,你可以查看 /proc/<pid>而不是你的 ps .. | grep ... | grep

  3. 当你有父 pid 时,你可以 grep "^Ppid:[[:space:]]*$pid" /proc/*/status并计算输出行以确定子进程的数量