首页 > 技术文章 > 【原创】利用Ubuntu的cron服务来定时启动和关闭motion

gengzj 2014-05-14 12:37 原文

【原创】利用Ubuntu的cron服务来定时启动和关闭motion


环境:

Ubuntu12.04


实现文件:

motion的配置文件motion.conf

启动motion的motionstart.c文件

停止motion的motionstop.c文件文件

用crontab -e命令添加的定时服务命令文件


实现方法:

首先,配置好文件motion.conf,运行motion进行测试,观察motion是否满足自己的需求。

然后,创建文件motionstart.c,执行gcc motionstart.c -o motionstart,生成可执行文件motionstart。

然后,创建文件motionstop.c,执行gcc motionstop.c -o motionstop,生成可执行文件motionstop。

然后,用crontab -e命令添加定时启动motionstart和定时启动motionstop命令。

最后,重启cron服务,/etc/init.d/cron  restart。


文件代码:

motion配置文件motion.conf

配置方法参考我的另一篇博客文章

【原创】Ubuntu监测动态环境(发送视频到邮箱、NAT模式下端口映射)


motionstart.c文件

/*************************************************************************
	> File Name: motionstart.c
	> Author: Geng
	> Mail: zhenjie.geng@gmail.com 
	> Created Time: 2014年05月14日 星期三 11时24分53秒
 ************************************************************************/

#include<stdio.h>
#include<unistd.h>

int main(void)
{
	execl("/usr/bin/motion", "motion", (char *)0);//在子进程中运行motion

	return 0;
}


motionstop.c文件

/*************************************************************************
	> File Name: motionstop.c
	> Author: Geng
	> Mail: zhenjie.geng@gmail.com 
	> Created Time: 2014年05月14日 星期三 11时33分26秒
 ************************************************************************/

#include<stdio.h>
#include<unistd.h>
#include<string.h>

int main(void)
{
    char motion_pid[15] = "\0";//从文件/home/geng/share/motion/motion.pid读motion的pid,保存到motion_pid数组中
	FILE *fp=NULL;//文件指针
		/*
		 * 下面几行代码是从文件/home/geng/share/motion/motion.pid中读取motion的pid值。
		 * 因为文件/home/geng/share/motion/motion.pid在motion运行后自动被创建,motion运行结束后又被自动删除,
		 * 所以,读取motion的pid的代码应该在motion运行后执行。
		 */
	    if((fp=fopen("/home/geng/share/motion/motion.pid","r"))==NULL) //以可读写的方式打开文件;若该文件存在则清空,若不存在就创建
	    {  //打开文件失败
	        printf("can not open!\n");
	        return -1;
	    }
	    fgets(motion_pid,sizeof(motion_pid),fp); 
		/*
		 *因为用fgets从文件中读到的数据存储到字符数组中后,会自动在数组所有字符后
		 *加上一个换行符'\n',所以需要用下面这行代码把得到的数据处理一下
		 */
		motion_pid[strlen(motion_pid)-1] = '\0';

		//向motion进程发送SIGINT信号,SIGINT信号的就是2.
		execl("/bin/kill", "kill", "-s", "2", motion_pid, (char *)0);

	return 0;
}

crontab -e命令添加的定时服务命令文件

在终端中执行  crontab -e

然后再打开的文件中末尾加上一下代码。

#每天晚上22点50分执行motionstart
50 22 * * * /root/motionstart
#每天早上点5分执行motionstop
05 08 * * * /root/motionstop

其他说明:

除了用C文件使用exec实现motion的启动和停止外,还可以使用shell脚本程序。如果要使用shell脚本,要注意的有两点:1.赋予脚本可执行的权限;2.脚本文件名称不能有后缀.sh,否则可能不能可靠运行脚本(这是看到网络上其他人说的,有待验证)。



推荐阅读