Today I changed the method of calling the hand detection agent. Originally, the hand detection agent is called by a thread that calls std::system() function. The problem here is that this method could not kill the agent when the main program is being terminated.
Now, I changed so that the agent is executed in an individual process using the fork() function. The fork() function creates a replica of the current process. New process gets the return value of 0 from the fork function, and old process gets the id of new process. Because I could essentially create new process and overwrite the program with execve() function, I can have more control of the process than the thread-based agent.
Original method :
void *hand_detection::ai_agent(void *data) {
std::string str = "python3 hand_detection_python.py --debug 0 --video ";
str += std::string(GlobalHandDetectionSystem::get_self()->video_device);
std::system(str.c_str());
// signal the main process that the program has ended
((bool*)data)[0] = false;
pthread_exit(0x00);
}
New method :
/* (Removed the ai_agent() function) */
void hand_detection::execute_agent(void) {
GlobalHandDetectionSystem *global_hand_info = GlobalHandDetectionSystem::get_self();
std::cout << "waiting for the agent to send the data...\n";
pid_t pid = fork();
if(pid == 0) {
execl("/usr/bin/python3" , "/usr/bin/python3" , "./hand_detection_python.py" , "--debug" , "0" , "--video" , global_hand_info->video_device , (char*)0x00);
exit(0);
}
global_hand_info->agent_process_id = pid;
...
You can see that because the new agent is a new process, we can terminate the agent all as we want :
kill(global_hand_info->agent_process_id , SIGKILL);