2016-02-12 123 views
1

是否可以檢查進程是否終止?Boost.Process檢查進程是否終止

我不想調用.wait(),因爲它是阻塞的,我想管理超時,之後我將終止該過程。

現在我有以下代碼:

child c = launch(exec, args, ctx); 
auto timeout = boost::posix_time::seconds(3); 
boost::this_thread::sleep(timeout); 
c.terminate(); 

,但它不會等待終止和不檢查過程正常temrinated。

+0

如何通過boost :: asio使用[async API](http://www.highscore.de/boost/process0.5/boost_process/tutorial.html#boost_process.tutorial.waiting_for_a_program_to_exit)? –

回答

1

這不是在boost.process 0.5(它是0.6),所以你需要自己實現它。這可以這樣做:

#if defined (BOOST_WINDOWS_API) 

template<typename Child> 
inline bool is_running(const Child &p, int & exit_code) 
{ 
    DWORD code; 
    //single value, not needed in the winapi. 
    if (!GetExitCodeProcess(p.proc_info.hProcess, &code)) 
     throw runtime_error("GetExitCodeProcess() failed"); 

    if (code == 259) //arbitrary windows constant 
     return true; 
    else 
    { 
     exit_code = code; 
     return false; 
    }  
} 

#elif defined(BOOST_POSIX_API) 

tempalte<typename Child> 
inline bool is_running(const Child&p, int & exit_code) 
{ 
    int status; 
    auto ret = ::waitpid(p.pid, &status, WNOHANG|WUNTRACED); 

    if (ret == -1) 
    { 
     if (errno != ECHILD) //because it no child is running, than this one isn't either, obviously. 
      throw std::runtime_error("is_running error"); 

     return false; 
    } 
    else if (ret == 0) 
     return true; 
    else //exited 
    { 
     if (WIFEXITED(status)) 
      exit_code = status; 
     return false; 
    } 
} 

#endif 

或者只是使用boost.process 0.6,如​​果你有C++ 11可用。