系统编程五
对话期:用secucrt软件远程登录一个用户的时候,就是创建了一个对话期(session)。
对话期和进程组都是为了方便给进程发信号而存在的。
./test 是在前台进程组运行
./test &是在后台进程组运行
精灵进程是就算关闭终端了,它还在运行。。只要主机不断电。他是在一个独立的空间默默的运行。
下面说一下创建精灵进程的步骤:
最先运行在前台组的程序是前台组的组长,它是不能调用setsid()函数,所以它只能产生一个子进程。但是这个子进程还是属于前台组那个进程组的,所以这时终端发信号给这个进程组的话,新的对话还是有可能收到信号,所以此时还不完美。此时调用setpgrp函数它就变成一个新的进程组了,跟之前的没联系了。可是此时新的对话期因为是祖先,所以还有可能也有权利创建一个终端,所以此时再生一个进程,这时它不是祖先了,就无法创建终端什么的。它就可以做它的隐士了,如下图所示:
程序:
int main(void)
{
pid_t a;
int max_fd, i;
/*********************************************
1. ignore the signal SIGHUP, prevent the
process from being killed by the shutdown
of the present controlling termination
**********************************************/
signal(SIGHUP, SIG_IGN);
/***************************************
2. generate a child process, to ensure
successfully calling setsid()
****************************************/
a = fork();
if(a > 0)
exit(0);
/******************************************************
3. call setsid(), let the first child process running
in a new session without a controlling termination
*******************************************************/
setsid();
/*************************************************
4. generate the second child process, to ensure
that the daemon cannot open a terminal file
to become its controlling termination
**************************************************/
a = fork();
if(a > 0)
exit(0);
/*********************************************************
5. detach the daemon from its original process group, to
prevent any signal sent to it from being delivered
**********************************************************/
setpgrp();
/*************************************************
6. close any file descriptor to release resource
**************************************************/
max_fd = sysconf(_SC_OPEN_MAX);
for(i=0; i<max_fd; i++)
close(i);
/******************************************
7. clear the file permission mask to zero
*******************************************/
umask(0);
/****************************************
8. change the process's work directory,
to ensure it won't be uninstalled
*****************************************/
chdir("/"); //选择根目录最安全了,因为根目录不会被卸载
// Congratulations! Now, this process is a DAEMON!
//Initialize the log file.
syslog(LOG_DAEMON, "I am a daemonAAA!");
openlog("daemon_test", LOG_CONS | LOG_PID, LOG_DAEMON);
return 0;
}