加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:05:51 所属栏目:百科 来源:网络整理
导读:我有一个套接字,在执行时充当服务器并响应一些结果. 首先我编译它:g -o daemon.cpp dictionary.cpp -lpthread c 11 然后执行:./ a 现在它将在某个端口上侦听请求. 我希望我创建一个目标文件a,它不应该手动执行.而是作为守护程序文件工作,它不断地监听请求.
我有一个套接字,在执行时充当服务器并响应一些结果.
首先我编译它: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 connectionnn");
        csock = (int *) malloc(sizeof(int));
        if ((*csock = accept(hsock,(sockaddr *) & sadr,&addr_size)) != -1) 
        {
            printf("---------------------nReceived connection from %sn",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 %dn",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 goto
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){
        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 connectionnn");
                csock = (int *) malloc(sizeof(int));
                *csock = accept(hsock,&addr_size);
                CHECK_THROW(*csock!=-1,-7);
                printf("---------------------nReceived connection from %sn",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 */  }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读