Skip to content

Instantly share code, notes, and snippets.

@ulidtko
Created September 27, 2025 22:06
Show Gist options
  • Select an option

  • Save ulidtko/7850191d9a06003929322880146542c1 to your computer and use it in GitHub Desktop.

Select an option

Save ulidtko/7850191d9a06003929322880146542c1 to your computer and use it in GitHub Desktop.
inotify api demo for keter issue #294
#!/bin/bash
test -x $(which inotifywait 2>/dev/null) || {
echo "Install inotifywait(1) -- usually in package called inotify-tools"
exit 1
}
#-- Uncomment to run with all sleeps disabled, for extra fun!
#sleep () { : noop; }
slow_write () {
echo "AAAA"; sleep 0.5
echo "BBBB"; sleep 0.5
echo "CCCC"; sleep 0.5
}
main () {
sleep 0.2; echo
echo 'Scenario A: creating file under target with direct open() write() close()'
sleep 0.2
slow_write > "$target"/direct-write.txt
sleep 0.2; echo
echo 'Scenario B: moving file into testdir (atomically)'
slow_write > "$tmpdir/atomic-mv.txt"
mv "$tmpdir"/atomic-mv.txt "$target"/
}
synchronize_to_watches_established () {
while IFS= read -r line; do
echo "$line"
test "$line" == "Watches established." && touch "$tmpdir"/established && echo "(SYNCED)"
done
}
tmpdir="$(mktemp -d --tmpdir test.XXX)"
target="$tmpdir"/watched-target
mkdir -vp "$target"
set -m # enable job-control; required for process-group kill
inotifywait --monitor "$target" -e CREATE -e MODIFY -e CLOSE_WRITE -e MOVED_TO 2>&1 \
| synchronize_to_watches_established \
& tracepid=$!
trap "kill -s INT -- -$tracepid; wait; rm -rf $tmpdir" EXIT
#-- Synchronize to "Watches established", then run main
while ! test -f "$tmpdir"/established; do sleep 0.1; done
main
@ulidtko
Copy link
Author

ulidtko commented Sep 27, 2025

$ ./inotify-test.sh
mkdir: created directory '/tmp/test.n2q/watched-target'
Setting up watches.
Watches established.
(SYNCED)

Scenario A: creating file under target with direct open() write() close()
/tmp/test.n2q/watched-target/ CREATE direct-write.txt
/tmp/test.n2q/watched-target/ MODIFY direct-write.txt
/tmp/test.n2q/watched-target/ MODIFY direct-write.txt
/tmp/test.n2q/watched-target/ MODIFY direct-write.txt
/tmp/test.n2q/watched-target/ CLOSE_WRITE,CLOSE direct-write.txt

Scenario B: moving file into testdir (atomically)
/tmp/test.n2q/watched-target/ MOVED_TO atomic-mv.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment