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>:
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
例如python脚本
* * * * * py crontab_test.py
当stdout缓冲12k左右个字符时,可以由try-catch捕获到errno=32的Broken Pipe异常
Exception: [Errno 32] Broken pipe
这个异常无法由signal中断机制捕获
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中断机制捕获
相关文章推荐
- Linux Rootkit之一:Linux Rootkit简介
- linux的io空间和内存空间
- Linux下的lds链接脚本详解
- linux下使用tar命令
- 一、Linux 学习注意事项
- Linux搭建SVN 服务器
- Linux系统如何查看版本信息
- 嵌入式Linux系统启动过程
- CentOS下安装postgresql 9.4
- Linux数据流重定向
- CentOS最小安装后如何联网
- Linux FrameBuffer详解
- linux上很方便的上传下载文件工具rz和sz
- [Linux] ubuntu 格式化u盘
- linux 中前后台问题
- 安装BCM43142 802.11b/g/n Linux 驱动
- linux下的文件IO缓冲区,及其相关操作
- Centos 7安装XFCE桌面
- linux 下find查找命令
- linux 命令