Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
process_group.h
Go to the documentation of this file.
1
5#pragma once
6
7#include <algorithm>
8#include <cerrno>
9#include <chrono>
10#include <csignal>
11#include <cstdint>
12#include <limits>
13#include <sys/wait.h>
14#include <thread>
15#include <unistd.h>
16
17namespace platf::process_group {
19 template<class Running>
20 bool wait_for_exit(Running running, std::chrono::steady_clock::duration timeout) {
21 const auto deadline = std::chrono::steady_clock::now() + timeout;
22 while (running()) {
23 const auto now = std::chrono::steady_clock::now();
24 if (now >= deadline) {
25 return false;
26 }
27 std::this_thread::sleep_until(std::min(deadline, now + std::chrono::milliseconds {10}));
28 }
29 return true;
30 }
31
32 inline bool valid(std::uintptr_t handle) {
33 // Never allow PID 0, -1, or our own group to become a broadcast kill.
34 return handle > 1 && handle <= static_cast<std::uintptr_t>(std::numeric_limits<pid_t>::max()) &&
35 static_cast<pid_t>(handle) != getpgrp();
36 }
37
38 inline bool running(std::uintptr_t handle) {
39 if (!valid(handle)) {
40 return false;
41 }
42 int result;
43 do {
44 result = kill(-static_cast<pid_t>(handle), 0);
45 } while (result < 0 && errno == EINTR);
46 // waitpid(-pgid) only sees our direct children. It returns ECHILD after a
47 // launcher exits even if Gamescope/Wine descendants still occupy the group.
48 // Signal 0 probes the entire group without reaping a child's exit status.
49 return result == 0 || errno != ESRCH;
50 }
51
52 inline bool signal(std::uintptr_t handle, int sig) {
53 if (!valid(handle)) {
54 errno = EINVAL;
55 return false;
56 }
57 int result;
58 do {
59 result = kill(-static_cast<pid_t>(handle), sig);
60 } while (result < 0 && errno == EINTR);
61 return result == 0 || errno == ESRCH;
62 }
63
64 // Only use during termination, when the application exit status is no longer
65 // needed. Liveness checks during normal streaming must not consume it.
66 inline void reap_children(std::uintptr_t handle) {
67 if (!valid(handle)) {
68 return;
69 }
70 for (;;) {
71 const auto result = waitpid(-static_cast<pid_t>(handle), nullptr, WNOHANG);
72 if (result > 0 || (result < 0 && errno == EINTR)) {
73 continue;
74 }
75 break;
76 }
77 }
78} // namespace platf::process_group
@ timeout
Timeout.
Definition common.h:438
bool wait_for_exit(Running running, std::chrono::steady_clock::duration timeout)