ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / arch / um / kernel / tempfile.c
1 /*
2  * Copyright (C) 2002 Jeff Dike (jdike@karaya.com)
3  * Licensed under the GPL
4  */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <string.h>
10 #include <errno.h>
11 #include <sys/param.h>
12 #include "init.h"
13
14 /* Modified from create_mem_file and start_debugger */
15 static char *tempdir = NULL;
16
17 static void __init find_tempdir(void)
18 {
19         char *dirs[] = { "TMP", "TEMP", "TMPDIR", NULL };
20         int i;
21         char *dir = NULL;
22
23         if(tempdir != NULL) return;     /* We've already been called */
24         for(i = 0; dirs[i]; i++){
25                 dir = getenv(dirs[i]);
26                 if((dir != NULL) && (*dir != '\0'))
27                         break;
28         }
29         if((dir == NULL) || (*dir == '\0')) 
30                 dir = "/tmp";
31         tempdir = malloc(strlen(dir) + 2);
32         if(tempdir == NULL){
33                 fprintf(stderr, "Failed to malloc tempdir, "
34                         "errno = %d\n", errno);
35                 return;
36         }
37         strcpy(tempdir, dir);
38         strcat(tempdir, "/");
39 }
40
41 int make_tempfile(const char *template, char **out_tempname, int do_unlink)
42 {
43         char tempname[MAXPATHLEN];
44         int fd;
45
46         find_tempdir();
47         if (*template != '/')
48                 strcpy(tempname, tempdir);
49         else
50                 *tempname = 0;
51         strcat(tempname, template);
52         if((fd = mkstemp(tempname)) < 0){
53                 fprintf(stderr, "open - cannot create %s: %s\n", tempname, 
54                         strerror(errno));
55                 return -1;
56         }
57         if(do_unlink && (unlink(tempname) < 0)){
58                 perror("unlink");
59                 return -1;
60         }
61         if(out_tempname){
62                 if((*out_tempname = strdup(tempname)) == NULL){
63                         perror("strdup");
64                         return -1;
65                 }
66         }
67         return(fd);
68 }
69
70 /*
71  * Overrides for Emacs so that we follow Linus's tabbing style.
72  * Emacs will notice this stuff at the end of the file and automatically
73  * adjust the settings for this buffer only.  This must remain at the end
74  * of the file.
75  * ---------------------------------------------------------------------------
76  * Local variables:
77  * c-file-style: "linux"
78  * End:
79  */