tmpfile.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. /*
  10. * pANS stdio -- tmpfile
  11. *
  12. * Bug: contains a critical section. Two executions by the same
  13. * user could interleave as follows, both yielding the same file:
  14. * access fails
  15. * access fails
  16. * fopen succeeds
  17. * fopen succeeds
  18. * unlink succeeds
  19. * unlink fails
  20. * As I read the pANS, this can't reasonably use tmpnam to generate
  21. * the name, so that code is duplicated.
  22. */
  23. #include "iolib.h"
  24. static char tmpsmade[FOPEN_MAX][L_tmpnam+1];
  25. static int ntmps = 0;
  26. static void rmtmps(void);
  27. FILE *tmpfile(void){
  28. FILE *f;
  29. static char name[]="/tmp/tf0000000000000";
  30. char *p;
  31. while(access(name, 0)==0){
  32. p=name+7;
  33. while(*p=='9') *p++='0';
  34. if(*p=='\0') return NULL;
  35. ++*p;
  36. }
  37. f=fopen(name, "wb+");
  38. if(f && ntmps<FOPEN_MAX){
  39. if(ntmps==0)
  40. atexit(rmtmps);
  41. strcpy(tmpsmade[ntmps++], name);
  42. }
  43. return f;
  44. }
  45. static void
  46. rmtmps(void)
  47. {
  48. int i;
  49. for(i=0; i<ntmps; i++)
  50. remove(tmpsmade[i]);
  51. }