📄 dameon.c
字号:
/*dameon.c创建守护进程*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAXFILE 65535
int main()
{
pid_t pc;
int i,fd,len;
char *buf="This is a Dameon\n";
len=strlen(buf);
pc=fork();//第一步
if(pc<0){
printf("error fork\n");
exit(1);
}else if(pc>0)
exit(0);
/*第二步*/
setsid();
/*第三步*/
chdir("/");
/*第四步*/
umask(0);
for(i=0;i<MAXFILE;i++)
/*第五步*/
close(i);
/*这时创建完守护进程,以下开始正式进入守护进程工作*/
while(1){
if((fd=open("/tmp/dameon.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0)
//O_APPEND:以添加方式打开文件,在打开文件同时,文件指针指向文件的末尾。
{
perror("open");
exit(1);
}
write(fd,buf,len+1);
close(fd);
sleep(10);
}
}
运行:
1、将该程序编译后运行,可以看到该程序每隔10s就会在对应的文件中输入相关的内容,并且使用ps可以看到该进程在后台运行。如下所示:
终端一 [root@localhost test] #./dameon
运行后可关闭该终端。
终端二:[root@localhost test]#tail -f /tmp/dameon.log
This is a Dameon
This is a Dameon
This is a Dameon
This is a Dameon
...
终端三: [root@localhost test]#ps -ef | grep dameon
76 root 1272 s ./dameon
85 root 1520 s grep dameon
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -