linux c创建后台进程

deamon守护进程是Linux下的一种特殊的进程,很多的时候我们需要自己写的进程作为后台进程来运行从而和console脱离起来。

方法是:

#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

int
daemon(int nochdir, int noclose)
{
	if (fork() != 0)
		_exit(0);
	if (nochdir == 0)
		(void) chdir("/");
	if (noclose == 0) {
		(void) close(0);
		(void) open("/dev/null", O_RDWR);
		(void) dup2(0, 1);
		(void) dup2(0, 2);
	}
	(void) setsid();
	if (fork() != 0)
		_exit(0);
	return (0);
}

 这样的话我们的进程就从console脱离了出来并作为一个daemon进程来运行。

man setsid;来查看setsid()函数的用法;

 

posted @ 2015-03-17 13:52  秋风微凉  阅读(1072)  评论(0编辑  收藏  举报