1

I am using Apache Thrift to set up a c++ server. On the server side I want to execute

execl("a.out","",(char *)NULL);

but either the above line of code is executed first or server.serve() is executed first. Is there any way for the server to start and have the line of code run on top of the server?

I tried putting it in the message_test function but I only want it to execute once not every time when I start up a client.

a.cpp:

 int main(){
     cout<<"I have started up"<<endl;
     string message;
     while (cin >> message){
         cout<<"your message is: "<<message<<endl;
     }
     cout<<"I have now exited"<<endl;
  }

Server.cpp

class ThforkServiceHandler : virtual public ThforkServiceIf {
     public:
     ThforkServiceHandler() {
       // Your initialization goes here

     }
     void message_test(const std::string& message) {
       // Your implementation goes here
        printf("message_test\n");
     }
 };

int main(int argc, char **argv) {
    int port = 9090;
    shared_ptr<ThforkServiceHandler> handler(new ThforkServiceHandler());
    shared_ptr<TProcessor> processor(new ThforkServiceProcessor(handler));
    shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
    shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
    shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory()); 
    TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
    server.serve();
    return 0;
}
Moeiz Riaz
  • 165
  • 2
  • 18

1 Answers1

1

According to the docs, execl() replaces the current process with the program called. On the other hand, server.serve() will block until someone forces the server to exit the server loop inside.

That explains why you get only one of the two. The one replaces the server and the other call blocks. In essence, either one of these two calls will be (more or less) the last thing that is executed in the server code.

I'd suggest to use a system() call or something like that instead.

Community
  • 1
  • 1
JensG
  • 13,148
  • 4
  • 45
  • 55
  • or something like `fork` and call `serve()` and `execl` in parallel processes. ThforkServiceHandler name even suggests it :) – Hcorg Jun 09 '15 at 11:31
  • Hey, In main(), I used fork , in the child I called execl() and in the parent I called serve() and it works. Now I am just trying to use dup2 and pipes and to keep the exel() open rather than exiting. so I can just keep calling it. – Moeiz Riaz Jun 10 '15 at 21:31
  • I'm glad you found the answer helpful to solve the issue. Now tell it the world! – JensG Jun 10 '15 at 21:42
  • Do you guys know of a way to keep the `while(cin >> message)` loop open forever? I tried using pipes but the program keeps closing after I close the pipes. – Moeiz Riaz Jun 11 '15 at 12:00