tmpfile.c 912 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * pANS stdio -- tmpfile
  3. *
  4. * Bug: contains a critical section. Two executions by the same
  5. * user could interleave as follows, both yielding the same file:
  6. * access fails
  7. * access fails
  8. * fopen succeeds
  9. * fopen succeeds
  10. * unlink succeeds
  11. * unlink fails
  12. * As I read the pANS, this can't reasonably use tmpnam to generate
  13. * the name, so that code is duplicated.
  14. */
  15. #include "iolib.h"
  16. static char tmpsmade[FOPEN_MAX][L_tmpnam+1];
  17. static int ntmps = 0;
  18. static void rmtmps(void);
  19. FILE *tmpfile(void){
  20. FILE *f;
  21. static char name[]="/tmp/tf0000000000000";
  22. char *p;
  23. while(access(name, 0)==0){
  24. p=name+7;
  25. while(*p=='9') *p++='0';
  26. if(*p=='\0') return NULL;
  27. ++*p;
  28. }
  29. f=fopen(name, "wb+");
  30. if(f && ntmps<FOPEN_MAX){
  31. if(ntmps==0)
  32. atexit(rmtmps);
  33. strcpy(tmpsmade[ntmps++], name);
  34. }
  35. return f;
  36. }
  37. static void
  38. rmtmps(void)
  39. {
  40. int i;
  41. for(i=0; i<ntmps; i++)
  42. remove(tmpsmade[i]);
  43. }