1#include "koh_create.h"23#include <errno.h>4#include <fcntl.h>5#include <unistd.h>67int koh_create_exclusive(const char *path, const void *data, size_t len) {8 int fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 0644);9 if (fd < 0) {10 return errno == EEXIST ? 0 : -1;11 }12 const char *bytes = (const char *)data;13 size_t written = 0;14 while (written < len) {15 ssize_t n = write(fd, bytes + written, len - written);16 if (n < 0) {17 if (errno == EINTR) {18 continue;19 }20 close(fd);21 unlink(path);22 return -1;23 }24 if (n == 0) {25 close(fd);26 unlink(path);27 return -1;28 }29 written += (size_t)n;30 }31323334 if (close(fd) != 0) {35 unlink(path);36 return -1;37 }38 return 1;39}