daemon函数使程序后台运行

daemon函数的作用就是让程序从控制终端分离开,以后台进程方式运行,服务器程序都是这么运行的。
查看一下man手册
NAME
       daemon - run in the background

SYNOPSIS
       #include <unistd.h>

       int daemon(int nochdir, int noclose);

DESCRIPTION
       The daemon() function is for programs wishing to detach themselves from the controlling terminal and run in the background as
system daemons.

       Unless the argument nochdir is non-zero, daemon() changes the current working directory to the root ("/").

       Unless the argument noclose is non-zero, daemon() will redirect standard input, standard output and standard error to
/dev/null.

RETURN VALUE
       (This  function  forks,  and  if  the fork() succeeds, the parent does _exit(0), so that further errors are seen by the child
only.)  On success zero will be returned.  If an
       error occurs, daemon() returns -1 and sets the global variable errno to any of the errors specified for the library functions
fork(2) and setsid(2).

描述:大致意义是说daemon()函数使程序从控制终端分离并且运行在后台如同系统守护进程一样。
参数:参数nochdir如果等于零进程的当前工作目录更改为root目录,否则当前工作目录保持不变;参数noclose如果等于零会则标准输入、标准输出、
标准错误重定向到/dev/null否则不会修改这些描述符。
返回值:成功返回0 失败返回-1并设置errno

下面是一个简单的实例

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>

#define ERR_EXIT(m) \
do\
{\
    perror(m);\
    exit(EXIT_FAILURE);\
}\
while (0);\

int main(int argc, char **argv)
{
    time_t t;
	FILE *fp_console = stdout;
	FILE *fp_file = fopen("daemon.log", "at");
	if (NULL == fp_file)
		ERR_EXIT("open error");

	if (argc >= 2 && 0 == memcmp("-d", argv[1], strlen("-d"))){//是否以后台进程的方式运行
		if (daemon(1, 1) == -1)
			ERR_EXIT("daemon error");

		fp_console = NULL;
	}

    while(1){
        t = time(0);
        char *buf = asctime(localtime(&t));
		//输出
		if (fp_console)
		{
			fprintf(fp_console, "%s", buf);
		}
        fwrite(buf,1,strlen(buf), fp_file);
		fflush(fp_file);
        sleep(60);      
    }
    return 0;
}

运行结果

添加-d 就会后台运行

猜你喜欢

转载自blog.csdn.net/qq_19825249/article/details/108093999