-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathUnixCancellationPipe.cs
53 lines (41 loc) · 1.59 KB
/
UnixCancellationPipe.cs
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
49
50
51
52
53
using static Vezel.Cathode.Unix.UnixPInvoke;
namespace Vezel.Cathode.Terminals.Unix;
[SuppressMessage("", "CA1001")]
internal sealed class UnixCancellationPipe
{
private readonly UnixVirtualTerminal _terminal;
private readonly AnonymousPipeServerStream _server;
private readonly AnonymousPipeClientStream _client;
public UnixCancellationPipe(UnixVirtualTerminal terminal)
{
_terminal = terminal;
_server = new(PipeDirection.Out);
_client = new(PipeDirection.In, _server.ClientSafePipeHandle);
}
public unsafe void PollWithCancellation(int handle, CancellationToken cancellationToken)
{
// Note that the runtime sets up a SIGPIPE handler for us.
var unused = false;
var pipeHandle = _client.SafePipeHandle;
pipeHandle.DangerousAddRef(ref unused);
try
{
var handles = (stackalloc[] { (int)pipeHandle.DangerousGetHandle(), handle });
using (var registration = cancellationToken.UnsafeRegister(
static state => Unsafe.As<UnixCancellationPipe>(state!)._server.WriteByte(42), this))
if (!_terminal.PollHandles(null, POLLIN, handles))
return;
// Were we canceled?
if ((handles[0] & POLLIN) != 0)
{
// Read the dummy byte that was written to indicate cancellation.
_ = _client.ReadByte();
throw new OperationCanceledException(cancellationToken);
}
}
finally
{
pipeHandle.DangerousRelease();
}
}
}