open_lock.c 383 B

12345678910111213141516171819
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include "open.h"
  6. int open_lock(const char *fn)
  7. {
  8. #ifdef O_CLOEXEC
  9. int fd = open(fn,O_RDWR | O_CLOEXEC);
  10. if (fd == -1) return -1;
  11. #else
  12. int fd = open(fn,O_RDWR);
  13. if (fd == -1) return -1;
  14. fcntl(fd,F_SETFD,1);
  15. #endif
  16. if (lockf(fd,F_LOCK,0) == -1) { close(fd); return -1; }
  17. return fd;
  18. }