#include <unistd.h>
#include 
<sys/types.h>
#include 
<sys/wait.h>
#include 
<signal.h>

class ProcessMap
{
private:
  map
<std::string, pid_t> m_process_map;

public:

const bool create_process(const std::string& process_name, const std::string& user_name);

const bool remove_process(const std::string& user_name);
};

//create child process and add to process map
const bool ProcessMap::create_process(const std::string& process_name, const std::string& user_name)
{
    QMServerMap::remove_process(user_name);

    pid_t pID 
= fork();
    
if (pID == 0)
    {
                
//you can add arguments for the child process if you like
        execl(process_name, NULL);
    }
    
else if (pID < 0)
    {
        
// failed to fork
        return false;
    }
    
else
    {
        
// parent
        m_process_map[user_name] = pID;
    }
    
return true;
}


//delete child process and remove from the process map
const bool QMServerMap::remove_process(const std::string& user_name)
{
    
if (m_process_map.find(user_name)!=m_process_map.end())
    {
        pid_t pid 
= m_process_map[user_name];
        
if (pid > 0)
        {
            kill(pid,SIGTERM);
            waitpid(pid, NULL, 
0);
        }
        m_process_map.erase(user_name);

        
return true;
    }
    
return false;
}

相关文章: