aboutsummaryrefslogtreecommitdiff
path: root/src/zenutil/process/exitwatcher.h
blob: 24906d7d0476f698f0d376664d130ee01693caf5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include <zencore/process.h>
#include <zencore/zencore.h>

#include <functional>
#include <memory>

namespace asio {
class io_context;
}

namespace zen {

/// Async process exit watcher.
///
/// Uses platform-specific mechanisms for scalable, non-polling exit detection:
///   Linux:   pidfd_open() + asio::posix::stream_descriptor
///   Windows: asio::windows::object_handle
///   macOS:   kqueue EVFILT_PROC/NOTE_EXIT + asio::posix::stream_descriptor
///
/// The callback is invoked exactly once when the process exits, posted to the
/// io_context. Call Cancel() to suppress the callback.
class ProcessExitWatcher
{
public:
	explicit ProcessExitWatcher(asio::io_context& IoContext);
	~ProcessExitWatcher();

	ProcessExitWatcher(const ProcessExitWatcher&) = delete;
	ProcessExitWatcher& operator=(const ProcessExitWatcher&) = delete;

	/// Begin watching the given process. The callback is posted to the io_context
	/// when the process exits. Only one Watch() may be active at a time.
	void Watch(const ProcessHandle& Handle, std::function<void(int ExitCode)> OnExit);

	/// Cancel any outstanding watch. The callback will not be invoked after this
	/// returns. Safe to call if no watch is active.
	void Cancel();

private:
	struct Impl;
	std::unique_ptr<Impl> m_Impl;
};

}  // namespace zen