疯狂的 crond 行为.不断制作失效的bash进程

2022-01-13 00:00:00 cron bash crontab centos php

我有一个看起来像这样的 crontab:

I have a crontab that looks like:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

0-59 * * * * /var/www/html/private/fivemin/zdaemon.php >> /dev/null &

尽可能简单,对吧?

zdaemon.php 是:

zdaemon.php which I am just testing with is:

#!/usr/bin/php
<?


while(true){
        sleep(1);
}

?>

无论何时运行,它都会像这样挂起:

Whenever it runs it hangs like:

root     15532  0.0  0.1 57228 1076 ?        Ss   19:09   0:00 crond
root     16681  0.0  0.1 72196 1428 ?        S    21:46   0:00 crond
root     16682  0.0  0.0     0    0 ?        Zs   21:46   0:00 [bash] <defunct>
root     16683  0.0  0.5 54800 5740 ?        S    21:46   0:00 /usr/bin/php /var/www/html/private/fivemin/zdaemon.php
root     16687  0.0  0.1 72196 1428 ?        S    21:47   0:00 crond
root     16688  0.0  0.0     0    0 ?        Zs   21:47   0:00 [bash] <defunct>
root     16689  0.0  0.5 54800 5740 ?        S    21:47   0:00 /usr/bin/php /var/www/html/private/fivemin/zdaemon.php

我整天都在用脑子敲墙.谁看过这个吗?有什么想法吗?

I have been banging my brain against a wall on this all day. Has anyone seen this before? Any ideas at all?

这是对以下内容的引用:Init.d 脚本挂起

This is a reference to: Init.d script hanging

推荐答案

僵尸进程本身并不一定是坏事.它表示 child 进程已经死亡,而 parent 进程尚未恢复其状态(使用 wait() 或相关的系统调用).

A zombie process is not necessarily a bad thing in itself. It indicates that the child process has died, and the parent process has not yet reaped its status (using wait() or a related system call).

发生的情况如下 - cron 对它启动的脚本中的 stderr 感兴趣(以便在脚本失败时通过电子邮件将其发送给您),因此它创建了一个 pipe,将脚本的 stderr 附加到写入端(文件描述符 2).然后 cron 坐在管道的读取端读取,等待脚本退出并读取 eof(read() 零字节)- 然后获取脚本的返回状态.

What is happening is as follows - cron is interested in stderr from the script it starts (so that it can email it to you should the script fail), therefore it creates a pipe which is attaches stderr of the script to write end (file descriptor 2). Then cron sits reading on the read end of the pipe, waiting for the script to exit and read eof (read() of zero bytes) - it then reaps the return status of the script.

在您的示例中,生成的守护程序继承了 stderr 文件描述符,因此当中间 shell 退出(并失效)时,管道由守护程序保持打开状态.因此,cron 永远不会读取 eof,因此永远不会获得返回状态.

In your example, the daemon spawned, inherits the stderr file descriptor, and therefore when the intermediate shell exits (and becomes defunct), the pipe is held open by the daemon. Therefore cron never reads eof and hence never reaps the return status.

解决方案是确保您的守护程序的 stderr 已关闭.这可以通过以下方式实现:

The solution is to ensure that stderr of your daemon is closed. This can be achieved as follows:

0-59 * * * * /var/www/html/private/fivemin/zdaemon.php >> /dev/null 2>&1 &

这会将 both stdout 和 stderr 写入 /dev/null

which will write both stdout and stderr to /dev/null

相关文章