使用daemon()让C程序运行在后台

在linux中,可以使用daemon()函数让程序运行在后台,这个函数的原型是:

#include <unistd.h>

int daemon(int nochdir, int noclose);

其中,如果 nochdir 为 0,则 daemon() 将当前工作目录改变为 "/",否则当前工作目录保持不变;

如果 nocolose 为 0,则 daemon() 将标准输入、标准输出、标准错误输出 重定向为 /dev/null,否则保持不变。

示例程序:

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>

void sighandler(int signum) {
   printf("Caught signal %d, coming out...\n", signum);
}

int main(int argc, char **args) {
	signal(SIGINT, sighandler);

	int ret = daemon(1, 1);
	if (ret != 0) {
		printf("server cannot running on background ...\n");
		exit(-1);
	}

	printf("server is running on background ...\n");
	while (true) {
		sleep(1);
		printf("message from background ...\n");
	}

	return 0;
}

运行结果:

$ ./run_bg
server is running on background ...
$ message from background ...
message from background ...
message from background ...
message from background ...
message from background ...
message from background ...
Caught signal 2, coming out...
message from background ...
message from background ...

从上面的运行结果来看,如果 daemon() 函数的 noclose 参数为1,那么在后台运行的程序依然使用标准输出来进行打印。同时,程序在后台运行时也可以正常接收信号。

猜你喜欢

转载自blog.csdn.net/choumin/article/details/111462217
今日推荐