daemon 进程的描述符奇怪的0,2,3

软件和网站开发以及相关技术探讨
回复
febwave
帖子: 39
注册时间: 2007-04-29 16:26

daemon 进程的描述符奇怪的0,2,3

#1

帖子 febwave » 2013-10-21 10:59

大家好:
最近我在学习守护进程,也写了个测试代码。
为了结合syslog,所以我把最后一段fd检查放在日志了。
现在遇到问题,如果直接使用变量fd记录的话,可以获取0,1,2,这个和书上一样。

代码: 全选

int            fd0;
int            fd1;
int            fd2;

fd0 = open("/dev/null", O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
但如果我直接

代码: 全选

syslog(LOG_INFO,"new_fd0--%d",open("/dev/null", O_RDWR) );
syslog(LOG_INFO,"new_fd1--%d",dup(0));
syslog(LOG_INFO,"new_fd2--%d",dup(0));
这时候输出的是0,2,3

请教在哪里有问题呢?


以下是全部代码,平台是ubuntu1204

代码: 全选


#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <syslog.h>
#include <iostream>
#include <sys/time.h>
#include <sys/resource.h>


using namespace std;

int main()
{
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!

	pid_t	child;

	// this is first level child for new session
	child = fork();
	if(child == -1)
	{
		exit(-1);
	}
	else if(child >0)
	{
		exit(0);
	}



	umask(0);
	setsid();

	chdir("/");



	// this is second level child for tty
	child = fork();
	if(child == -1)
	{
		exit(-1);
	}
	else if(child >0)
	{
		exit(0);
	}

	openlog("test.d",LOG_CONS|LOG_PID,0);
		// close file description from 0 to max
	unsigned int openfileIndex= 0;
	struct rlimit rl;
	getrlimit(RLIMIT_NOFILE,&rl);
	syslog(LOG_INFO,"fd_max--%ld",rl.rlim_max);
	for(openfileIndex = 0;openfileIndex < rl.rlim_max;openfileIndex++)
	{
		close(openfileIndex);
	}

	/*
	int            fd0;

	int            fd1;
	int            fd2;


	fd0 = open("/dev/null", O_RDWR);
	fd1 = dup(0);
	fd2 = dup(0);

	syslog(LOG_INFO,"fd0--%d",fd0 );
	syslog(LOG_INFO,"fd1--%d",fd1);
	syslog(LOG_INFO,"fd2--%d",fd2);
*/

	syslog(LOG_INFO,"new_fd0--%d",open("/dev/null", O_RDWR) );
	syslog(LOG_INFO,"new_fd1--%d",dup(0));
	syslog(LOG_INFO,"new_fd2--%d",dup(0));

	openfileIndex = 0;
	while(1)
	{
		sleep(5);
		syslog(LOG_INFO,"%d",openfileIndex++);
	}
	return 0;
}

回复