Skip to content

Commit 9e1acd3

Browse files
Copilotenghitalo
andcommitted
Add cross-platform usage examples and documentation
Co-authored-by: enghitalo <63821277+enghitalo@users.noreply.github.com>
1 parent e493d03 commit 9e1acd3

1 file changed

Lines changed: 98 additions & 0 deletions

File tree

vlib/os/notify/EXAMPLES.md

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
# Cross-Platform Usage Example for os.notify
2+
3+
This example demonstrates how to write cross-platform code using `os.notify` that gracefully handles platform differences.
4+
5+
```v
6+
import os
7+
import os.notify
8+
import time
9+
10+
fn main() {
11+
mut notifier := notify.new() or {
12+
eprintln('Failed to create notifier: ${err}')
13+
return
14+
}
15+
defer {
16+
notifier.close() or {}
17+
}
18+
19+
// Create a pipe for demonstration
20+
pipefd := [2]int{}
21+
if C.pipe(&pipefd[0]) != 0 {
22+
eprintln('Failed to create pipe')
23+
return
24+
}
25+
reader, writer := pipefd[0], pipefd[1]
26+
defer {
27+
os.fd_close(reader)
28+
os.fd_close(writer)
29+
}
30+
31+
// Add read event - works on all platforms
32+
notifier.add(reader, .read) or {
33+
eprintln('Failed to add reader: ${err}')
34+
return
35+
}
36+
37+
// Try to add peer_hangup - will fail on macOS, succeed on Linux
38+
notifier.add(reader, .peer_hangup) or {
39+
// Gracefully handle unsupported feature
40+
eprintln('Note: peer_hangup not supported: ${err}')
41+
// Continue with just read events
42+
}
43+
44+
// Your event loop
45+
for {
46+
events := notifier.wait(1 * time.second)
47+
for event in events {
48+
if event.kind.has(.read) {
49+
// Handle read
50+
data, _ := os.fd_read(event.fd, 1024)
51+
println('Read: ${data}')
52+
}
53+
if event.kind.has(.peer_hangup) {
54+
// This will only trigger on Linux
55+
println('Peer disconnected')
56+
break
57+
}
58+
}
59+
}
60+
}
61+
```
62+
63+
## Platform-Specific Code
64+
65+
You can also use conditional compilation for platform-specific features:
66+
67+
```v
68+
import os.notify
69+
70+
fn setup_notifier(mut notifier notify.FdNotifier, fd int) ! {
71+
$if linux {
72+
// Use all available features on Linux
73+
notifier.add(fd, .read | .peer_hangup, .edge_trigger)!
74+
} $else $if macos {
75+
// Use only supported features on macOS
76+
notifier.add(fd, .read, .edge_trigger)!
77+
}
78+
}
79+
```
80+
81+
## Checking Platform Capabilities
82+
83+
For library code that needs to work across platforms, use error handling:
84+
85+
```v
86+
fn add_with_hangup(mut notifier notify.FdNotifier, fd int) ! {
87+
// Try with hangup first
88+
notifier.add(fd, .read | .hangup) or {
89+
// If it fails, fall back to just read
90+
if err.msg().contains('hangup') {
91+
notifier.add(fd, .read)!
92+
} else {
93+
// Some other error, propagate it
94+
return err
95+
}
96+
}
97+
}
98+
```

0 commit comments

Comments
 (0)