5

実行中にサーバーとして機能し、いくつかの結果を返すソケットが 1 つあります。最初にコンパイルします:g++ -o a daemon.cpp dictionary.cpp -lpthread c++11 次に実行します:./a

これで、いくつかのポートでリクエストをリッスンします。

オブジェクトファイルを作成したいのですがa、手動で実行しないでください。むしろ、リクエストを継続的にリッスンするデーモンファイルとして機能します。

idを使用してfork()何かできることがわかりました。しかし、以下のコードで場所を修正できませんでした:

削除した変数宣言:

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 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, 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 %d\n", errno);
        goto FINISH;
    }

FINISH:
    free(csock);
    return 0;
}
4

1 に答える 1

2
#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 connectionn\n");
                csock = (int *) malloc(sizeof(int));
                *csock = accept(hsock, (sockaddr *) & sadr, &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, 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 */  }
于 2013-09-18T10:59:56.727 に答える