]> git.saurik.com Git - apple/system_cmds.git/blob - dynamic_pager.tproj/dynamic_pager.c
9fb33691c3422bc26b32a4693c2c73ea20ddb304
[apple/system_cmds.git] / dynamic_pager.tproj / dynamic_pager.c
1
2 #define mig_external
3
4 #include <sys/mount.h>
5 #include <sys/stat.h>
6 #include <sys/sysctl.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <dirent.h>
12
13 /*
14 * We don't exit with a non-zero status anywhere here for 2 reasons:
15 * - the kernel can continue to create swapfiles in "/private/var/vm/swapfile<index>"
16 * - we want this job to run only once at boot and exit regardless of whether:
17 * -- it could clean up the swap directory
18 * -- it could set the prefix for the swapfile name.
19 */
20
21
22 static void
23 clean_swap_directory(const char *path)
24 {
25 DIR *dir;
26 struct dirent *entry;
27 char buf[1024];
28
29 dir = opendir(path);
30 if (dir == NULL) {
31 fprintf(stderr,"dynamic_pager: cannot open swap directory %s\n", path);
32 exit(0);
33 }
34
35 while ((entry = readdir(dir)) != NULL) {
36 if (entry->d_namlen>= 4 && strncmp(entry->d_name, "swap", 4) == 0) {
37 snprintf(buf, sizeof buf, "%s/%s", path, entry->d_name);
38 unlink(buf);
39 }
40 }
41
42 closedir(dir);
43 }
44
45 int
46 main(int argc, char **argv)
47 {
48 char default_filename[] = "/private/var/vm/swapfile";
49 int ch;
50 int err=0;
51 static char tmp[1024];
52 struct statfs sfs;
53 char *q;
54 char fileroot[512];
55
56 seteuid(getuid());
57 strcpy(fileroot, default_filename);
58
59 while ((ch = getopt(argc, argv, "F:")) != EOF) {
60 switch((char)ch) {
61
62 case 'F':
63 strncpy(fileroot, optarg, 500);
64 break;
65
66 default:
67 (void)fprintf(stderr,
68 "usage: dynamic_pager [-F filename]\n");
69 exit(0);
70 }
71 }
72
73 /*
74 * get rid of the filename at the end of the swap file specification
75 * we only want the portion of the pathname that should already exist
76 */
77 strcpy(tmp, fileroot);
78 if ((q = strrchr(tmp, '/')))
79 *q = 0;
80
81 /*
82 * Remove all files in the swap directory.
83 */
84 clean_swap_directory(tmp);
85
86 if (statfs(tmp, &sfs) == -1) {
87 /*
88 * Setup the swap directory.
89 */
90
91 if (mkdir(tmp, 0755) == -1) {
92 (void)fprintf(stderr, "dynamic_pager: cannot create swap directory %s\n", tmp);
93 }
94 }
95
96 chown(tmp, 0, 0);
97
98 err = sysctlbyname("vm.swapfileprefix", NULL, 0, fileroot, sizeof(fileroot));
99 if (err) {
100 (void)fprintf(stderr, "Failed to set swapfile name prefix with error: %d\n", err);
101 }
102
103 return (0);
104 }