您的位置:首页 > 运维架构 > Linux

linux定时任务cron的一点研究

2015-06-13 22:10 543 查看
1 crontab -e修改之后不需要重启crontab即可生效

2 cron的启动多个子进程CROND<短进程>,每一个子进程对应crontab表中的一行

3 CROND关闭了stdin,stdout,stderr管道,可以从/proc/pid/fd中确认<假定CROND进程id为15576>:

[root@localhost fd] # pwd
/proc/15576/fd
[root@localhost fd]# ls
lrwx------. 1 root root 64 Jun 13 21:10 0 -> /dev/null
lrwx------. 1 root root 64 Jun 13 21:10 1 -> /dev/null
lrwx------. 1 root root 64 Jun 13 21:10 2 -> /dev/null
lr-x------. 1 root root 64 Jun 13 21:10 5 -> inotify
lr-x------. 1 root root 64 Jun 13 21:10 6 -> pipe:[10395853]


4 crontab中的定时任务继承了CROND的管道(包括stdout,stderr),所以必须关闭子进程的标准输出和错误输出

否则子进程的1或者2管道会发生异常,导致程序异常退出

例如:crontab_task 1>/dev/null 2>&1

或者在shell中禁止使用 echo、printf和logger -s,但是允许使用logger记录日志

或者在python中禁止使用print

或者在c/c++程序中禁止使用printf和cout

5 crontab_test举例

例如shell脚本

* * * * * sh crontab_test.sh

#!/bin/sh
int=1
while(( $int<=1000))
do
#echo "echo test $int 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
#printf "printf test $int 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\n"
#logger -s "logger -s test $int 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
logger "logger test $int 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
let "int++"
sleep 0.1
done
当stdout缓冲4k个字符时,程序自动退出

例如python脚本

* * * * * py crontab_test.py

#!/usr/bin/python
import signal
import syslog
import time

def Log(msg):
print msg
syslog.syslog(msg)

signal.signal(signal.SIGPIPE, signal.SIG_IGN)
int=1
try:
while int<=1000:
Log("test %d 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" % int)
int+=1
time.sleep(0.1)
except Exception, e:
Log("Exception: %s" % str(e))


当stdout缓冲12k左右个字符时,可以由try-catch捕获到errno=32的Broken Pipe异常

Exception: [Errno 32] Broken pipe

这个异常无法由signal中断机制捕获
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: