在守护进程中启动一个新进程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在守护进程中启动一个新进程相关的知识,希望对你有一定的参考价值。

以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()接口创建一个进程,启动指定的应用程序。

以上是关于在守护进程中启动一个新进程的主要内容,如果未能解决你的问题,请参考以下文章

Flutter错误无法启动守护进程

Linux 守护进程三

python 守护进程

Linux守护进程的启动方法

Linux下怎么查看某个守护进程或者所有的守护进程?

Linux守护进程/精灵进程的创建