c – 从服务器套接字创建守护程序处理

c – 从服务器套接字创建守护程序处理,第1张

概述我有一个套接字,在执行时充当服务器并响应一些结果. 首先我编译它:g -o daemon.cpp dictionary.cpp -lpthread c 11 然后执行:./ a 现在它将在某个端口上侦听请求. 我希望我创建一个目标文件a,它不应该手动执行.而是作为守护程序文件工作,它不断地监听请求. 我看到使用fork()id可以做一些事情.但我在下面的代码中无法更正地方: 我已删除变量decla 我有一个套接字,在执行时充当服务器并响应一些结果.
首先我编译它:g -o daemon.cpp dictionary.cpp -lpthread c 11
然后执行:./ a

现在它将在某个端口上侦听请求.

我希望我创建一个目标文件a,它不应该手动执行.而是作为守护程序文件工作,它不断地监听请求.

我看到使用fork()ID可以做一些事情.但我在下面的代码中无法更正地方:

我已删除变量declation:

using namespace std;using namespace boost;voID *SocketHandler(voID *);int main(int argv,char **argc){    pthread_t thread_ID = 0;    hsock = socket(AF_INET,SOCK_STREAM,0);    if (hsock == -1)     {        printf("Error initializing socket %dn",errno);        goto FINISH;    }    p_int = (int *) malloc(sizeof(int));    *p_int = 1;    if ((setsockopt(hsock,Sol_SOCKET,SO_REUSEADDR,(char *) p_int,sizeof(int)) == -1)         || (setsockopt(hsock,SO_KEEPAliVE,sizeof(int)) == -1))     {        printf("Error setting options %dn",errno);        free(p_int);        goto FINISH;    }    free(p_int);    my_addr.sin_family = AF_INET;    my_addr.sin_port = htons(host_port);    memset(&(my_addr.sin_zero),8);    my_addr.sin_addr.s_addr = INADDR_ANY;    if (bind(hsock,(sockaddr *) & my_addr,sizeof(my_addr)) == -1)     {        fprintf(stderr,"Error binding to socket,make sure nothing else is Listening on this port %dn",errno);        goto FINISH;    }    if (Listen(hsock,10) == -1)     {        fprintf(stderr,"Error Listening %dn",errno);        goto FINISH;    }    //Now lets do the server stuff    addr_size = sizeof(sockaddr_in);    int pID;    pID_t pID=fork();    if(pID<0)          exit(EXIT_FAILURE);        else if(pID>0){    //this is parent process,exit Now         exit(EXIT_SUCCESS); // again no goto   }   else{        //this is child or daemon       unmask();   pID_t childID = setsID();    while (true)     {        printf("waiting for a connectionn\n");        csock = (int *) malloc(sizeof(int));        if ((*csock = accept(hsock,(sockaddr *) & sadr,&addr_size)) != -1)         {            printf("---------------------nReceived connection from %s\n",inet_ntoa(sadr.sin_addr));            pthread_create(&thread_ID,&SocketHandler,(voID *) csock);            pthread_detach(thread_ID);        }         else         {            fprintf(stderr,"Error accepting %dn",errno);        }    sleep(60);    }FINISH:    ;}voID *SocketHandler(voID *lp){       char *ch;/* stores references to 50 words. */    char *ch2[50] = { 0 };      char *excluded_string;    char *word;    if ((bytecount = recv(*csock,(char*) rcv.c_str(),rcv.length(),0)) == -1)     {         fprintf(stderr,"Error receiving data %d \n",errno);        goto FINISH;    }        do     {        bytesReceived = recv(*csock,buffer.data(),buffer.size(),0);        // append string from buffer.        if ( bytesReceived == -1 )         {             fprintf(stderr,errno);            goto FINISH;        }         else             rcv.append( buffer.cbegin(),buffer.cend() );    } while ( bytesReceived == MAX_BUF_LENGTH );    word = strtok(& rcv[0]," ");    while (word!= NulL)     {        skp = BoyerMoore_skip(word,strlen(word) );        if(skp != NulL)        {            i++;            printf("this also \n");            word = strtok(NulL," ");            continue;        }        printf("\n Word %s \n",word);        bfr << word << " ";        result_string = bfr.str();        word = strtok(NulL," ");        j++;     }    ss<<result_string;    while (std::getline(ss,item,' '))     {        writable.push_back(item);    }    for (std::vector < std::string >::iterator it = writable.begin(); it != writable.end(); it++)        ++src[*it];    std::transform(src.begin(),src.end(),std::inserter(dst,dst.begin()),mytransform);    rec=dst.begin();       for (auto it = dst.begin(); it != dst.end(); ++it)        std::cout << it->second << ":" << it->first << std::endl;    if ((bytecount = send(*csock,(char *)ar,i *sizeof(int),0)) == -1)     { // Here we cant send lenth-1. It consIDer exact        fprintf(stderr,"Error sending data %d\n",errno);        goto FINISH;    }FINISH:    free(csock);    return 0;}
解决方法
#include <sys/types.h> #include <unistd.h>pID_t pID=fork();if(pID<0)exit(EXIT_FAILURE); //see no gotoelse if(pID>0){  //this is parent process,exit Now   exit(EXIT_SUCCESS); // again no goto }  else{   //this is child or daemon    unmask();     pID_t childID = setsID();     while(true){        myTask();    //Run the Process    sleep(60);       }  }

好的,我研究了你的程序并进行了修改.这就是你的主要代码应该是这样的.

using namespace std;  using namespace boost;  #define CHECK_THROW(condtion,code) if(condition) throw code  voID *SocketHandler(voID *);  int OpenSockets();  int main(int argv,char **argc)  {    try{        pID_t pID = fork();        CHECK_THROW(pID<0,-5);        if(pID==0)        {            //this is child or daemon                    mode_t oldMask,newMask;             oldMask=unmask(newMask);            pID_t childID = setsID();            int hsock = OpenSocket();            CHECK_THROW(Listen(hsock,10) == -1,-4);            addr_size = sizeof(sockaddr_in);            while (true)             {                printf("waiting for a connectionn\n");                csock = (int *) malloc(sizeof(int));                *csock = accept(hsock,&addr_size);                CHECK_THROW(*csock!=-1,-7);                printf("---------------------nReceived connection from %s\n",inet_ntoa(sadr.sin_addr));                pthread_t thread_ID = pthread_create(&thread_ID,(voID *) csock);                pthread_detach(thread_ID);            }        }    }    catch(int IError)    {        switch(IError)        {            case -4: fprintf(stderr,errno); break;            case -7: fprintf(stderr,errno); break;        }      }  }  int OpenSockets()  {      // Create your socket and return the socket handle from this function   }  voID *SocketHandler(voID *lp){    /*blah blah */  }
总结

以上是内存溢出为你收集整理的c – 从服务器套接字创建守护程序处理全部内容,希望文章能够帮你解决c – 从服务器套接字创建守护程序处理所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1226834.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存