什么是守护进程:
守护进程是在后台运行不受控端控制的进程,通常情况下守护进程在系统启动时自动运行
守护进程的名称通常以d结尾,比如sshd、xinetd、crond等
创建守护进程的步骤:
调用fork(),创建新进程,他会是将来的守护进程
在父进程中调用exit,保证子进程不是进程组长
调用setsid创建新的会话期
将当前目录改为根目录
将标准输入。标准输出、标准错误重定向到 /dev/null
具体代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <signal.h>
#include <sys/wait.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int setup_daemon();
int main()
{
setup_daemon();
for(;;);
return 0;
}
int setup_daemon()
{
pid_t pid;
pid = fork();
if(pid == -1)
{
ERR_EXIT("fork error");
}
if(pid > 0)
{
exit(0);
}
setsid();
chdir("/");
for(int i = 0;i < 3; ++i)
{
close(i);
}
open("/dev/null",O_RDWR);
dup(0);
dup(0);
}
现在可以使用ps -ef查看守护进程:
怎么关闭守护进程?
输入
killall a.out
即可,杀死进程。
daemon函数:
功能:创建一个守护进程
参数:
nochdir:=0将当前目录更改至“/”
noclose:=0将标准输入、标准输出。标准错误重定向至“/dev/null”
函数原型:
intdaemon(int nochdir,int noclose);
使用daemon函数也是可以创建守护进程的。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <signal.h>
#include <sys/wait.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int setup_daemon();
int main()
{
// setup_daemon();
daemon(0,0);
for(;;);
return 0;
}
int setup_daemon()
{
pid_t pid;
pid = fork();
if(pid == -1)
{
ERR_EXIT("fork error");
}
if(pid > 0)
{
exit(0);
}
setsid();
chdir("/");
for(int i = 0;i < 3; ++i)
{
close(i);
}
open("/dev/null",O_RDWR);
dup(0);
dup(0);
}
查看结果:
会发现daemon有两个参数;
两个参数为0 ,表示更改目录为根目录,对输入输出输出错误进行重定向。
两个参数为1,表示不更改目录为根目录,不对输入输出输出错误进行重定向。