您的位置:首页 > 运维架构 > Linux

Linux开发--守护进程的创建

2017-05-01 14:26 447 查看

1 简介

    守护进程是在后台运行不受终端控制的进程,通常情况下守护进程在系统启动时自动运行,用户关闭终端窗口或注销也不会影响守护进程的运行,只能kill掉。守护进程的名称通常以d结尾,比如sshd、xinetd、crond等

    实际上一般的进程(前后台) 在关闭终端窗口后,会收到 SIGHUP 信号导致中断,可以使用 nohup command args > /dev/null 2>&1 & 来忽略 hangup 信号,或者直接使用 setsid command args 来使进程成为守护进程。需要注意的是,使用 nohup 时的父进程id 为终端的进程id,使用 setsid 时的父进程id 为 1(即 init 进程
id)。

2 守护进程的创建



#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fs.h>

int main (void)
{
pid_t pid;
int i;

/* create new process */
pid = fork ( );
if (pid == -1)
return -1;

else if(pid != 0)
exit (EXIT_SUCCESS);

/* create new session and process group */
if (setsid ( ) == -1)
return -1;

/* set the working directory to the root directory */
if (chdir (”/”) == -1)
return -1;

/* close all open files--NR_OPEN is overkill, but works */
for (i = 0; i < NR_OPEN; i++)
close (i);

/* redirect fd’s 0,1,2 to /dev/null */
open (”/dev/null”, O_RDWR); /* stdin    */
dup (0);                    /* stdout   */
dup (0);                    /* stderror */

/* do its daemon thing... */

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Linux 守护进程