By analogy with std::thread
, I've written an RAII POSIX process:
class posix_process
{
public:
explicit posix_process(std::function<void()> proc_main)
: _pid(fork())
{
if (_pid == -1)
throw std::system_error(errno, std::generic_category(), "fork");
if (_pid == 0)
proc_main();
}
pid_t pid() const
{
return _pid;
}
int wait(int options = 0) const
{
int wstatus = 0;
const pid_t r = waitpid(_pid, &wstatus, options);
if (r == -1)
throw std::system_error(errno, std::generic_category(), "waitpid");
return wstatus;
}
private:
// Disable copy and move
posix_process(const posix_process&) = delete;
posix_process(posix_process&&) = delete;
posix_process& operator=(posix_process) = delete;
pid_t _pid;
};
My main hesitation is that the child process ends up in a potentially weird state where the entire thing runs inside a constructor that was called in the parent process.
- Is this a good idea?
- What are the implications of making the class swappable by swapping
_pid
(and therefore, with minimal extra effort, moveable)?
boost::process::child
? You may be able to use that, or if not, to take inspiration from it. \$\endgroup\$