从服务器套接字创建守护进程处理



>我有一个套接字,它在执行时充当服务器并响应一些结果。首先我编译它:g++ -o a daemon.cpp dictionary.cpp -lpthread c++11然后执行:./a

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

想要那个我创建目标文件a,它不应该手动执行。而是作为守护程序文件工作,它不断侦听请求。

我看到使用fork() id可以做一些事情。但是我无法更正以下代码中的位置:

我删除了变量分类:

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, SOL_SOCKET, SO_KEEPALIVE, (char *) p_int, 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), 0, 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, 0, &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, "Error receiving data %d n", 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);    
   }
  }

好的,我研究了您的程序并进行了更改。这就是 main 中的代码应该是什么样子的。

  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, (sockaddr *) & sadr, &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, 0, &SocketHandler, (void *) csock);
                pthread_detach(thread_id);
            }
        }
    }
    catch(int ierror)
    {
        switch(ierror)
        {
            case -4: fprintf(stderr, "Error listening %dn", errno); break;
            case -7: fprintf(stderr, "Error accepting %dn", errno); break;
        }
      }
  }

  int OpenSockets()
  { 
     // Create your socket and return the socket handle from this function 
  }
  void *SocketHandler(void *lp){    /*blah blah */  }

最新更新