1. 程式人生 > >在守護進程中啟動一個新進程

在守護進程中啟動一個新進程

gis users man channel catch hat 進程 bject callback

以websocketpp的example為基礎, #include <websocketpp/config/asio_no_tls.hpp> #include <websocketpp/server.hpp> #include <iostream> #include <stdio.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #import <Foundation/Foundation.h> typedef websocketpp::server<websocketpp::config::asio> server; using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; typedef server::message_ptr message_ptr; /*喚起指定的應用程序啟動*/ void launchAppliction(char* appPath) { //appPath指向可執行文件的絕對地址 NSTask *softTask = [[NSTask alloc]init]; NSString * strPath = [NSString stringWithUTF8String:appPath]; [softTask setLaunchPath:strPath]; // [softTask setArguments:[NSArray arrayWithObjects:@"hello world", "2016", nil]];//設置運行參數 [softTask launch]; } /*創建進程,啟動應用程序*/ void make_process() { char app[] = "/Users/liuxuetao/work/sampleApp.app/Contents/MacOS/sampleApp"; launchAppliction(app); } // Define a callback to handle incoming messages void on_message(server* s, websocketpp::connection_hdl hdl, message_ptr msg) { std::cout << "on_message called with hdl: " << hdl.lock().get() << " and message: " << msg->get_payload() << std::endl; // check for a special command to instruct the server to stop listening so // it can be cleanly exited. if (msg->get_payload() == "stop-listening") { s->stop_listening(); return; } std::string a_str = msg->get_payload(); std::string b_str = "startprocess"; int ret = strcmp(a_str.c_str(),b_str.c_str()); if ( ret == 0 ) { make_process(); return; } try { s->send(hdl, msg->get_payload(), msg->get_opcode()); } catch (const websocketpp::lib::error_code& e) { std::cout << "Echo failed because: " << e << "(" << e.message() << ")" << std::endl; } } int main() { // Create a server endpoint server echo_server; try { // Set logging settings echo_server.set_access_channels(websocketpp::log::alevel::all); echo_server.clear_access_channels(websocketpp::log::alevel::frame_payload); // Initialize Asio echo_server.init_asio(); // Register our message handler echo_server.set_message_handler(bind(&on_message,&echo_server,::_1,::_2)); // Listen on port 9002 echo_server.listen(9060); // Start the server accept loop echo_server.start_accept(); // Start the ASIO io_service run loop echo_server.run(); } catch (websocketpp::exception const & e) { std::cout << e.what() << std::endl; } catch (...) { std::cout << "other exception" << std::endl; } return 0; } 當收到了遠程發來的指令startprocess後,守護進程會調用make_process()接口創建一個進程,啟動指定的應用程序。

在守護進程中啟動一個新進程