Linux创建后台进程

void setdaemon(const char * pid_file)
{
	pid_t pid;

	if(!pid_file)
	{
		return;
	}
	if((pid = fork()) < 0)
	{
		exit(-1);
	}
	if(pid)
	{
		exit(0);
	}
	setsid();
	if ((pid = fork()) < 0)
	{
  		exit(-1);
	}
	if (pid)
 	{
  		exit(0);
 	}
 	write_pid(pid_file);
}
void test()
{
	setdaemon("daemon.pid");
	while(1)
	{
		print("daemon process!\n");
		sleep(1);
	}
}
void main()
{
	pid_t pid = -1;
	int exitcode = 0;
	
	pid = fork();
	if(pid == 0)
	{
		test();
	}
	pid = wait(&exitcode);
	exit(0);
}

版权声明:本文为sinat_27261621原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。