flock-child.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /** IPC-controlled lock holder; acknowledgements follow settled syscalls or close. */
  2. import assert from 'node:assert/strict';
  3. import { once, on } from 'node:events';
  4. import { closeSync, openSync } from 'node:fs';
  5. import { tryLockExclusive } from '../../packages/entry/lib/flock.js';
  6. const messages = on(process, 'message');
  7. let fd = openSync(process.argv[2], 'a+', 0o600);
  8. try {
  9. await send({ type: 'ready' });
  10. for await (const [command] of messages) {
  11. if (command === 'close') {
  12. closeSync(fd);
  13. fd = undefined;
  14. await send({ type: 'closed' });
  15. break;
  16. }
  17. assert.equal(command, 'tryLock');
  18. let reply;
  19. try {
  20. await tryLockExclusive(fd);
  21. reply = { type: 'locked' };
  22. } catch (error) {
  23. reply = { type: 'error', code: error.code, errno: error.errno, syscall: error.syscall };
  24. }
  25. await send(reply);
  26. }
  27. } finally {
  28. await messages.return();
  29. if (fd !== undefined) closeSync(fd);
  30. if (process.connected) {
  31. const disconnected = once(process, 'disconnect');
  32. process.disconnect();
  33. await disconnected;
  34. }
  35. }
  36. function send(message) {
  37. return new Promise((resolve, reject) => {
  38. process.send(message, (error) => error ? reject(error) : resolve());
  39. });
  40. }