记录一下Linux守护进程的学习过程,主要关于Linux下命令的使用。
Tips: [ ]内为需要在命令行输入的命令; \n为按回车键;
1.用vim写程序
[vim daemon.c] 新建文件daemon.c文件,界面跳转,按[a],开始编辑c程序(标志为左下角变为INSERT),输入相关代码,代码写完后,输入[:wq \n](有冒号)保存代码退出vim。
2.用gcc编译程序
[gcc -c daemon.c] 无错误的话什么也看不到,生成目标文件
[gcc -o daemon daemon.o] 生成可执行的程序
需要查看目录下的文件列表,[ls],即可看到 daemon daemon.c daemon.o
3.执行daemon程序
[./daemon]程序开始运行,什么也看不到
4.查看日志文件
老师的要求是在日志文件中每隔10s写入当前时间,我的日志文件名为writetime.log
[tail -f /tmp/writetime.log]
即可看到日志文件内容的变化,即每10s输出一次当前时间。
5.kill daemon
先查看daemon程序的PID号,[ps -ef | grep daemon],最右边一列找到 ./daemon,然后看这一行的左边那一串数字,就是进程号PID
然后[kill PID],PID用上面的进程号代替即可kill daemon,此时[tail -f /tmp/writetime.log]的话日志文件不变化。
代码与截图如下:
/**
* Author: Kaituo Xu
* Date: 2015/3/19
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
int i, fd;
time_t timep;
char *buf = NULL;
pid = fork();
if( pid < 0 ) {
printf("Error fork!\n");
exit(1);
}
else if( pid > 0 ) {
exit(0) /*Step1.Kill parent process*/
}
setsid(); /*Step2.Creat new conversation*/
chdir("/"); /*Step3.change directory*/
umask(0); /*Step4.Set mask as 0*/
for( i = 0; i < getdtablesize(); i++) {
close(i);
} /*Step5.close file descriptor*/
/*创建完守护进程,以下开始正式进入守护进程工作*/
while(1) {
if( (fd = open("/tmp/writetime.log", O_CREAT|O_WRONLY|O_APPEND, 0600)) < 0) {
printf("Open file error\n");
exit(1);
}
timep = time(NULL);
buf = ctime(&timep);
write(fd, buf, strlen(buf)+1);
close(fd);
sleep(10);
}
exit(0);
}
版权归作者本人,转载请注明出处。