Skip to content

Instantly share code, notes, and snippets.

@aw
Last active May 7, 2018 06:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aw/4ca813f8571fda85b20bacfd50f84f07 to your computer and use it in GitHub Desktop.
Save aw/4ca813f8571fda85b20bacfd50f84f07 to your computer and use it in GitHub Desktop.
Create a file atomically in PicoLisp using native

PicoLisp's (native) can be used to create files atomically

The C equivalent would be:

open("atomic.file", O_RDWR|O_CREAT|O_EXCL, 0644);

PicoLisp:

# The flags can be read from sysdefs, but here we define them manually (Linux)
(setq
  O_RDWR  2   #(in '("@src64/sysdefs") (from "O_RDWR") (read))
  O_CREAT 64  #(in '("@src64/sysdefs") (from "O_CREAT") (read))
  O_EXCL  128 #(in '("@src64/sysdefs") (from "O_EXCL") (read))
  )

# The file mode 0644 is octal and must be converted to int
(native "@" "open" 'I "atomic.file" (| O_RDWR O_CREAT O_EXCL) (oct "0644"))
# -> 3
(native "@" "open" 'I "atomic.file" (| O_RDWR O_CREAT O_EXCL) (oct "0644"))
# -> -1

First call is successful (3), second call fails (-1), as expected.

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