- 论坛徽章:
- 0
|
最近要把一个原来的程序改成daemon的,因为之前debug信息都是直接使用printf打印到stdout上的,因此我想做成daemon时还保留我这种debug的方式,于是想重定向stdin和stdout,stderr,我自己写了个测试程序,把stdin重定向到打开/dev/null/的这个句柄上,stdout重定向到./klsa/klsa.log,stderr重定向到./klsa/klsa_err.log中,然后我用printf和perror测试了下发现并没有写到./klsa/klsa.log和./klsa/klsa_err.log中,大家解释下这是为什么?
代码如下:
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
*
* agent_daemon.c : make push_agent daemonify
*
* Author: tyz,if you compile error,feel free to contact me
* Created on 2009年10月12日, 下午8:22
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#define MAXFD 64
/**
* daemon_init:
*
* Detach agent daemon from the controlling terminal
*/
int daemon_init(void)
{
int i;
pid_t pid;
if ( (pid = fork()) < 0)
return (-1);
else if (pid)
exit(0);/* parent terminates */
/* child 1 continues... */
if (setsid() < 0)/* become session leader */
return (-1);
//signal(SIGHUP, SIG_IGN);
if ( (pid = fork()) < 0)
return (-1);
else if (pid)
exit(0);/* child 1 terminates */
/* child 2 continues... */
chdir("/");/* change working directory */
/* close off file descriptors */
for (i = 0; i < MAXFD; i++)
close(i);
/* redirect stdin, stdout, and stderr to /dev/null */
open("/dev/null", O_RDONLY);
open("./klsa/klsa.log", O_RDWR);
open("./klsa/klsa_err.log", O_RDWR);
//openlog(pname, LOG_PID, facility);
return (0);/* success */
}
int main(int argc,char **argv)
{
printf("\r\r\rkkkkkkkkkkkkkkkkkkkkkk\n") ;
/* mkdir in the /var/lib/ */
system("mkdir ./klsa") ;
/* create two files to redirect stdin and stdout */
fopen("./klsa/klsa.log", "a+"); /* stdout fd=1*/
fopen("./klsa/klsa_err.log", "a+"); /* stderr fd=2 */
daemon_init() ;
while(1)
{
printf("hehehehe\n") ;
perror("tyzTest:\n") ;
write(stdout,"hhhhhh\n",1) ;
close(stdout) ;
sleep(10) ;
}
return 0 ;
}
|
|
|