??????Linux????????????????????????daemon????????????????????????
????int daemon (int __nochdir?? int __noclose);
???????__nochdir????0?????л?????????????????__noclose?0???????????????????????????/dev /null??
??????????????????ú?????????????????????daemon??????linux?′????????????????е??
?????????????????????????????д???????test.c
#include <unistd.h>
#include <stdio.h>
int do_sth()
{
//Add what u want
return 0;
}
int main()
{
daemon(0??0);
while ( 1 )
{
do_sth();
sleep(1);
}
}
????????????
????[leconte@localhost daemon]$ gcc -o test test.c
????[leconte@localhost daemon]$ ./test
????????????????????ps????????????????????????????id?1????init????
??????lsof??test???????????????????????????????0??1??2?????????/dev/null
??????????????????????????????(cwd)?????/??daemon??????????????????daemon???????????????????????????????? ????????
????daemon????????????????????????????£?
????#include <unistd.h>
????int daemon(int nochdir?? int noclose);
????1?? daemon()???????????????????????????????????????????е????
????2?? ??nochdir?0???daemon??????????????root(“/”)??
????3?? ??noclose?0???daemon???????STDIN?? STDOUT?? STDERR???????/dev/null??
????daemon???????????£?
int daemon( int nochdir??  int noclose )
{
pid_t pid;
if ( !nochdir && chdir("/") != 0 ) //???nochdir=0????????"/"????
return -1;
if ( !noclose ) //??????noclose???
{
int fd = open("/dev/null"?? O_RDWR);
if ( fd  <  0 )
return -1;
/* ????????????????????/dev/null??
?????????????????κ?????????????????????????
*/
dup(fd?? 0);
dup(fd?? 1);
dup(fd?? 2);
close(fd);
}
pid = fork();  //?????????.
if (pid  <  0)  //???
return -1;
if (pid > 0)
_exit(0); //??????е????????????????????????????????????????????.
//?????? daemon???????е???????
if ( setsid()  < 0 )   //?????μ????????????????????????????
return -1;
return 0;  //???????daemon?????
}
???????????Linux?????μ????????daemon??????????????????????д?????????????????????????????????????????????????????ο????????????Linux?????????????????