zabbix守护进程例子分析:
很好的一个守护进程例子,贴出来,分析一下!
- /******************************************************************************
- * *
- * Function: daemon_start *
- * *
- * Purpose: init process as daemon *
- * *
- * Parameters: allow_root - allow root permision for application *
- * *
- * Return value: *
- * *
- * Author: Alexei Vladishev *
- * *
- * Comments: it doesn't allow running under 'root' if allow_root is zero *
- * *
******************************************************************************/
- int daemon_start(int allow_root)
- {
- pid_t pid;
- struct passwd *pwd;
- struct sigaction phan;
- char user[7] = "zabbix";
- /* running as root ?*/
- if((0 == allow_root) && (0 == getuid() || 0 == getgid()))
- {
- pwd = getpwnam(user); //从密码文件中取得指定帐号的数据
- if (NULL == pwd)
- {
- zbx_error("User %s does not exist.",
- user);
- zbx_error("Cannot run as root !");
- exit(FAIL);
- }
- if(setgid(pwd->pw_gid) ==-1) //设置真实组识别码
- {
- zbx_error("Cannot setgid to %s [%s].",
- user,
- strerror(errno));
- exit(FAIL);
- }
- #ifdef HAVE_FUNCTION_INITGROUPS
- if(initgroups(user, pwd->pw_gid) == -1) //初始化组清单,/etc/group中
- {
- zbx_error("Cannot initgroups to %s [%s].",
- user,
- strerror(errno));
- exit(FAIL);
- }
- #endif /* HAVE_FUNCTION_INITGROUPS */
- if(setuid(pwd->pw_uid) == -1) //设置用户识别码
- {
- zbx_error("Cannot setuid to %s [%s].",
- user,
- strerror(errno));
- exit(FAIL);
- }
- #ifdef HAVE_FUNCTION_SETEUID
- if( (setegid(pwd->pw_gid) ==-1) || (seteuid(pwd->pw_uid) == -1) )
- {//重新设置当前进程的有效用户,组识别码
- zbx_error("Cannot setegid or seteuid to zabbix [%s].", strerror(errno));
- exit(FAIL);
- }
- #endif /* HAVE_FUNCTION_SETEUID */
- }
- if( (pid = zbx_fork()) != 0 ) //创建进程
- {
- exit( 0 );
- }
- setsid(); //创建一个新的对话期
- signal( SIGHUP, SIG_IGN ); //设置信号
- if( (pid = zbx_fork()) !=0 )
- {
- exit( 0 );
- }
- /* This is to eliminate warning: ignoring return value of chdir */
- if(-1 == chdir("/")) //设置工作目录
- {
- assert(0);
- }
- umask(0002); //设置新建文件的权限遮罩
- redirect_std(CONFIG_LOG_FILE);
- #ifdef HAVE_SYS_RESOURCE_SETPRIORITY
- if(setpriority(PRIO_PROCESS,0,5)!=0) //设置程序进程执行优先权
- {
- zbx_error("Unable to set process priority to 5. Leaving default.");
- }
- #endif /* HAVE_SYS_RESOURCE_SETPRIORITY */
- /*------------------------------------------------*/
- if( FAIL == create_pid_file(APP_PID_FILE)) //pid 文件
- {
- exit(FAIL);
- }
- /* phan.sa_handler = child_signal_handler;*/
- phan.sa_sigaction = child_signal_handler;
- sigemptyset(&phan.sa_mask);
- phan.sa_flags = SA_SIGINFO;
- sigaction(SIGINT, &phan, NULL);
- sigaction(SIGQUIT, &phan, NULL);
- sigaction(SIGTERM, &phan, NULL);
- sigaction(SIGPIPE, &phan, NULL);
- zbx_setproctitle("main process");
- return MAIN_ZABBIX_ENTRY(); //进入开始调用的主函数
- }
Zabbix守护进程例子的分析就到这里了。下一节:Linux下如何安装Cacti
【编辑推荐】