守护进程, 说白了, 就是已经成年的进程, 比较独立, 切割了一切与父进程相关的东西。 通常, 我们可以在孤儿进程的基础上做文章, 如下:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int pid = fork();
    if(pid < 0)
    {
		return 1;
    }

	if(pid > 0)
	{
		return 1;
	}
	
    setsid();   // 子进程成为新组的组长进程
    chdir("/");
    umask(0);
    for(unsigned int i = 0; i < 1024; i++)
    {
		close(i);
	}

	
	// this is a daemon


	return 0;
}
       守护进程有什么用呢? 他在后台孤单单地为你服务, 比如我们常见的crond和sshd进程。

       太简单, 不值得多说。




本文转载:CSDN博客