草庐IT

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

coder 2024-02-25 原文

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

最佳答案

#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 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 */  }

关于c++ - 从服务器套接字创建守护进程处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18866380/

有关c++ - 从服务器套接字创建守护进程处理的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  5. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  6. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  7. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  8. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  9. ruby - 如何使用 RSpec::Core::RakeTask 创建 RSpec Rake 任务? - 2

    如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake

  10. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

随机推荐