mkostemps.c 676 B

12345678910111213141516171819202122232425262728293031
  1. #define _BSD_SOURCE
  2. #include <string.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <errno.h>
  6. #include "libc.h"
  7. char *__randname(char *);
  8. int __mkostemps(char *template, int len, int flags)
  9. {
  10. size_t l = strlen(template);
  11. if (l<6 || len>l-6 || memcmp(template+l-len-6, "XXXXXX", 6)) {
  12. errno = EINVAL;
  13. return -1;
  14. }
  15. flags -= flags & O_ACCMODE;
  16. int fd, retries = 100;
  17. do {
  18. __randname(template+l-len-6);
  19. if ((fd = open(template, flags | O_RDWR | O_CREAT | O_EXCL, 0600))>=0)
  20. return fd;
  21. } while (--retries && errno == EEXIST);
  22. memcpy(template+l-len-6, "XXXXXX", 6);
  23. return -1;
  24. }
  25. weak_alias(__mkostemps, mkostemps);
  26. weak_alias(__mkostemps, mkostemps64);