Linux守护进程

基础概念

进程组

  • 每个进程除了有一个进程ID之外,还属于一个进程组。
  • 进程组是一个或多个进程的集合,同一进程组中的各进程接收来自同一终端的各种信号。
  • 每个进程组有一个组长进程。组长进程的进程组ID等于其进程ID。

会话

会话(session)是一个或多个进程组的集合,进程调用 setsid 函数(原型:pid_t setsid(void) )建立一个会话。进程调用setsid函数建立一个新会话,如果调用此函数的进程不是一个进程组的组长,则此函数创建一个新会话。具体会发生以下3件事:

  • 该进程变成新会话的会话首进程(sessionleader,会话首进程是创建该会话的进程)。此时,该进程是新会话的唯一进程。
  • 该进程成为一个新进程组的组长进程。新进程组ID是该调用进程的进程ID。
  • 该进程没有控制终端。如果调用setsid之前该进程有一个控制终端,那么这种联系也被切断。

如果该调用进程已经是一个进程组的组长,则此函数返回出错。为了保证不处于这种情况,通常先调用fork,然后使其父进程终止,而子进程则继续。因为子进程继承了父进程的进程组ID,而其进程ID是重新分配的,两者不可能相等,这就保证了子进程不是一个进程组的组长。

C 复制代码
void daemonize(const char *cmd)
{
	int	i, fd0, fd1, fd2;
	pid_t pid;
	struct rlimit rl;
	struct sigaction sa;


    /*
	 * Clear file creation mask.
	 */
	umask(0);

	/*
	 * Get maximum number of file descriptors.
	 */
	if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
		err_quit("%s: can't get file limit", cmd);

	/*
	 * Become a session leader to lose controlling TTY.
	 */
	if ((pid = fork()) < 0)
		err_quit("%s: can't fork", cmd);
	else if (pid != 0) /* parent */
		exit(0);
	setsid();

	/*
	 * Ensure future opens won't allocate controlling TTYs.
	 */
	sa.sa_handler = SIG_IGN;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	if (sigaction(SIGHUP, &sa, NULL) < 0)
		err_quit("%s: can't ignore SIGHUP", cmd);
	if ((pid = fork()) < 0)
		err_quit("%s: can't fork", cmd);
	else if (pid != 0) /* parent */
		exit(0);

	/*
	 * Change the current working directory to the root so
	 * we won't prevent file systems from being unmounted.
	 */
	if (chdir("/") < 0)
		err_quit("%s: can't change directory to /", cmd);

	/*
	 * Close all open file descriptors.
	 */
	if (rl.rlim_max == RLIM_INFINITY)
		rl.rlim_max = 1024;
	for (i = 0; i < rl.rlim_max; i++)
		close(i);

	/*
	 * Attach file descriptors 0, 1, and 2 to /dev/null.
	 */
	fd0 = open("/dev/null", O_RDWR);
	fd1 = dup(0);
	fd2 = dup(0);

	/*
	 * Initialize the log file.
	 */
	openlog(cmd, LOG_CONS, LOG_DAEMON);
	if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
		syslog(LOG_ERR, "unexpected file descriptors %d %d %d",
		  fd0, fd1, fd2);
		exit(1);
	}
}
相关推荐
rui锐rui9 分钟前
大模型模型部署和暴露接口
linux·运维·服务器
Clownseven10 分钟前
云防火墙(安全组)配置指南:从入门到精通端口开放 (2025)
服务器·安全
XMAIPC_Robot20 分钟前
RK3568/RK3588 KVM系统虚拟化解决方案
网络·fpga开发·边缘计算
孙克旭_29 分钟前
day030-Shell自动化编程-函数
linux·运维·自动化
IT葛大侠36 分钟前
OSPF域内路由
运维·网络·计算机网络
筏.k37 分钟前
C++ 网络编程(10) asio处理粘包的简易方式
java·网络·c++
地衣君10 小时前
RISC-V 开发板 + Ubuntu 23.04 部署 open_vins 过程
linux·ubuntu·risc-v
5:0010 小时前
云备份项目
linux·开发语言·c++
码农101号10 小时前
Linux中shell编程表达式和数组讲解
linux·运维·服务器
云道轩11 小时前
升级centos 7.9内核到 5.4.x
linux·运维·centos