linux – 检查从同一bash脚本启动的后台进程的运行状态
我必须编写一个bash脚本,根据传递的命令行参数在后台启动进程,如果成功运行启动程序则返回.
这是我想要实现的伪代码 if [ "$1" = "PROG_1" ] ; then ./launchProg1 & if [ isLaunchSuccess ] ; then echo "Success" else echo "failed" exit 1 fi elif [ "$1" = "PROG_2" ] ; then ./launchProg2 & if [ isLaunchSuccess ] ; then echo "Success" else echo "failed" exit 1 fi fi 脚本不能等待或睡眠,因为它将由另一个关键任务c程序调用,并且需要高吞吐量(每秒没有启动进程),而且进程的运行时间未知.脚本既不需要捕获任何输入/输出,也不需要等待已启动的进程完成. 我没有成功尝试以下方法: #Method 1 if [ "$1" = "KP1" ] ; then echo "The Arguement is KP1" ./kp 'this is text' & if [ $? = "0" ] ; then echo "Success" else echo "failed" exit 1 fi elif [ "$1" = "KP2" ] ; then echo "The Arguement is KP2" ./NoSuchCommand 'this is text' & if [ $? = "0" ] ; then echo "Success" else echo "failed" exit 1 fi #Method 2 elif [ "$1" = "CD5" ] ; then echo "The Arguement is CD5" cd "doesNotExist" & PROC_ID=$! echo "PID is $PROC_ID" if kill -0 "$PROC_ID" ; then echo "Success" else echo "failed" exit 1 fi #Method 3 elif [ "$1" = "CD6" ] ; then echo "The Arguement is CD6" cd .. & PROC_ID=$! echo "PID is $PROC_ID" ps -eo pid | grep "$PROC_ID" && { echo "Success"; exit 0; } ps -eo pid | grep "$PROC_ID" || { echo "failed" ; exit 1; } else echo "Unknown Argument" exit 1 fi 运行脚本会产生不可靠的输出.方法1,2总是返回成功,而方法3在检查之前完成流程执行时返回失败. 这是在GNU bash上测试的示例,版本4.1.2(1)-release(x86_64-redhat-linux-gnu)和GNU bash,版本4.3.11(1)-release(x86_64-pc-linux-gnu) [scripts]$./processStarted3.sh KP1 The Arguement is KP1 Success [scripts]$./processStarted3.sh KP2 The Arguement is KP2 Success ./processStarted3.sh: line 13: ./NoSuchCommand: No such file or directory [scripts]$./processStarted3.sh CD6 The Arguement is CD6 PID is 25050 failed 正如类似问题所示,我不能使用进程名称,因为one process may be executed several times和others无法应用. 我没有尝试过screen和tmux,因为获得在生产服务器上安装它们的权限并不容易(但如果这是剩下的唯一选择,那么会这样做) UPDATE 进程完成执行或程序异常终止时无关紧要.通过脚本启动的程序不会以任何方式进行跟踪(因此我们不会将pid存储在任何表中,也不会出现使用deamontools的必要性). @Etan Reisner @Vorsprung 前面提到的#Method3可以很好地限制在ps -eo pid |之前终止的限制进程grep“$PROC_ID”&& {echo“成功”;退出0;可以执行检查. 解决方法
这是一个示例,它将显示一个过程的结果,无论它是否成功启动.
#!/bin/bash $1 & #executes a program in background which is provided as an argument pid=$! #stores executed process id in pid count=$(ps -A| grep $pid |wc -l) #check whether process is still running if [[ $count -eq 0 ]] #if process is already terminated,then there can be two cases,the process executed and stop successfully or it is terminated abnormally then if wait $pid; then #checks if process executed successfully or not echo "success" else #process terminated abnormally echo "failed (returned $?)" fi else echo "success" #process is still running fi #Note: The above script will only provide a result whether process started successfully or not. If porcess starts successfully and later it terminates abnormally then this sciptwill not provide a correct result (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |