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 17 static char tmpsmade[FOPEN_MAX][L_tmpnam+1]; 18 static int ntmps = 0; 19 20 static void rmtmps(void); 21 tmpfile(void)22FILE *tmpfile(void){ 23 FILE *f; 24 static char name[]="/tmp/tf0000000000000"; 25 char *p; 26 while(access(name, 0)==0){ 27 p=name+7; 28 while(*p=='9') *p++='0'; 29 if(*p=='\0') return NULL; 30 ++*p; 31 } 32 f=fopen(name, "wb+"); 33 if(f && ntmps<FOPEN_MAX){ 34 if(ntmps==0) 35 atexit(rmtmps); 36 strcpy(tmpsmade[ntmps++], name); 37 } 38 return f; 39 } 40 41 static void rmtmps(void)42rmtmps(void) 43 { 44 int i; 45 46 for(i=0; i<ntmps; i++) 47 remove(tmpsmade[i]); 48 } 49