Daemonizing多线程服务器

时间:2012-10-29 04:48:48

标签: c++ c multithreading

我正在编写一个必须在守护进程模式下运行的多线程Web服务器。我编写了代码,但程序在守护进程模式下运行时崩溃了。如果我不包含守护服务器的代码,程序运行正常。谁能告诉我哪里出错了?

pid_t pid,cid;
pid = fork();
if(pid<0)
{
exit(EXIT_FAILURE);
 }
if(pid>0)
{
    exit(EXIT_SUCCESS);
 }
umask(0);
cid=setsid();
std::cout<<"Process id after:"<<pid<<std::endl;
std::cout<<"Session id:"<<cid<<std::endl;
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);

pthread_t t1,t2;
pthread_t threads[threadnum];
pthread_attr_t attr;
if ((s = socket(AF_INET, soctype, 0)) < 0) {
    perror("socket");
    exit(1);
}
pthread_attr_init(&attr);
pthread_create(&t1,NULL,setup_server,NULL);  // thread for accepting the requests
pthread_create(&t2,NULL,scheduler,NULL);     // thread for scheduling the requests

1 个答案:

答案 0 :(得分:0)

以下代码行的目的是什么:

if(pid>0)
{
    exit(EXIT_SUCCESS);
}

如果您需要立即退出子进程,那么根本不要分叉您的程序。

另外,请发布功能setup_server()和scheduler()以帮助您完成程序。