Linux?????daemon??????д???????
???????????? ???????[ 2014/3/14 9:40:26 ] ???????????? Linux
??????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?????????????????
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11