#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
void usage(){
printf("usage: daemon [command]+\n");
}
int main(int argc, char *argv[]) {
if( argc < 2 ){
usage();
exit(1);
}
pid_t pid;
pid = fork();
if (pid < 0) {
fprintf(stderr, "cant fork()\n");
exit(1);
} else if (pid > 0) {
// end parent process
exit(0);
}
umask(0);
pid_t sid = setsid();
if (sid < 0) {
fprintf(stderr, "cant setsid()\n");
exit(1);
}
if ((chdir("/")) < 0) {
fprintf(stderr, "cant chdir()\n");
exit(1);
}
int i;
for (i=getdtablesize();i>=0;--i){
close(i);
}
// handle standard I/O
i=open("/dev/null",O_RDWR);
dup(i);
dup(i);
// execute command, and don't return
execvp(argv[1],argv+1);
return 0;
}
参考ページ
http://systhread.net/texts/200506cdaemon1.php
http://www.enderunix.org/documents/eng/daemon.php
No comments:
Post a Comment