#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
typedef void (*Sigfunc)(int);
void reap_status() {
int pid;
int status;
while((pid = wait3(&status, WNOHANG, NULL)>0));
}
void daemon_init(int s) {
int childpid, fd, fdtablesize;
int ret;
signal(SIGTTOU,SIG_IGN);
signal(SIGTTIN,SIG_IGN);
signal(SIGTSTP,SIG_IGN);
childpid=fork();
if(childpid == -1)
error(1,errno,"fork error!");
else if(childpid >0)
exit(0);
if(setsid()== -1)
error(1,0,"setsid error!");
childpid=fork();
if(childpid == -1)
error(1,errno,"fork error!");
else if(childpid >0)
exit(0);
/*
if(setpgrp(0,getpid())<0)
error(1,0,"setpgrp error!");
if((fd = open("/dev/tty",O_RDWR))>0){
ioctl(fd,TIOCNOTTY,NULL);
close(fd);
}
*/
for(fd=0, fdtablesize = getdtablesize(); fd < fdtablesize; fd++)
if(s != fd)
close(fd);
chdir("/");
umask(0);
signal(SIGCLD, (Sigfunc)reap_status);
openlog("hello",LOG_PID,0);
}
void process_server(int s, struct sockaddr_in * remote) {
char buff[128];
int len;
send(s, "hello/n!", 6, 0);
}
int main(int argc, char **argv) { struct sockaddr_in remote; char *hname, *sname; int s, c, len; if(argc < 2) error(1,0,"parameters less than 2"); else if(argc == 2) { hname = NULL; sname = argv[1]; } else if(argc == 3) { hname = argv[1]; sname = argv[2]; } s = server(hname, sname,"tcp"); daemon(s); len = sizeof(struct sockaddr); while(1) { if((c=accept(s,(struct sockaddr *)&remote,&len))<=0) error(1,errno,"accept error!"); process_server(c,&remote); } close(s); close(c); exit(0);}