请解释下面Shell脚本中 if开头的整行代码的意思,你见过它的应用场景么?
1
2
3
4
5
6
|
if
(
kill
-0 $pid 2>
/dev/du11
)
then
echo
"oldboy"
else
echo
"oldgirl"
fi
|
面试题:请解释if (kill -0 $pid 2>/dev/null)代码的意思?
1
2
3
4
5
6
|
if
(
kill
-0 $pid 2>
/dev/null
)
then
echo
"oldboy"
else
echo
"oldgirl"
fi
|
老男孩解答要点:
-
kill -0 $pid中的-0表示不发送任何信号给PID对应的进程,但是仍会对变量值PID对应的进程是否存在进行检查,如果$pid对应的进程存在,则返回0,不存在返回1。
-
2>/dev/null不输出错误信息。
-
系统里的应用场景是MySQL的/etc/init.d/mysqld脚本中停止MySQL服务的脚本代码段。
-
使用/etc/init.d/mysqld stop命令执行脚本关闭数据库的程序代码如下:
'stop')
# Stop daemon. We usea signal here to avoid having to know the
# root password.
iftest-s"$mysqld_pid_file_path"
then
mysqld_pid=`cat "$mysqld_pid_file_path"`
if (kill-0$mysqld_pid2>/dev/null)
then
echo$echo_n"Shutting down MySQL"
kill$mysqld_pid
# mysqld shouldremove the pid file when it exits, so wait for it.
wait_for_pid removed "$mysqld_pid""$mysqld_pid_file_path"; return_value=$?
else
log_failure_msg "MySQL server process #$mysqld_pidis not running!"
rm"$mysqld_pid_file_path"
fi
# Delete lock forRedHat / SuSE
if test-f"$lock_file_path"
then
rm-f"$lock_file_path"
fi
exit$return_value
else
log_failure_msg "MySQLserver PID file could not be found!"
fi
;;本文转自 李导 51CTO博客,原文链接:http://blog.51cto.com/lidao/1911141