首先,在 Linux 下清理缓存是毫无意义的,只有弊,没有利。原因可参考下文。
[Linux ate my ram!]
http://www.linuxatemyram.com/
然而有些用户就是坚持要清理缓存,牺牲性能也愿意,于是就有了以下清理缓存的方法:
# echo 3 > /proc/sys/vm/drop_caches
执行完上述命令,我们可以观察到 drop_caches 的值一直保持在3,没有变回0:
# cat /proc/sys/vm/drop_caches 3
如果这个值一直为3,系统会一直不停地清理缓存吗? 不会的,只有执行对 drop_caches 的写操作的时候,才会触发清理缓存:
/* Linux/kernel/sysctl.c */
1350 {
1351 .procname = "drop_caches",
1352 .data = &sysctl_drop_caches,
1353 .maxlen = sizeof(int),
1354 .mode = 0644,
1355 .proc_handler = drop_caches_sysctl_handler,
1356 .extra1 = &one,
1357 .extra2 = &four,
1358 },
/* Linux/fs/drop_caches.c */
42 int drop_caches_sysctl_handler(struct ctl_table *table, int write,
43 void __user *buffer, size_t *length, loff_t *ppos)
44 {
45 int ret;
46
47 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
48 if (ret)
49 return ret;
50 if (write) {
51 static int stfu;
52
53 if (sysctl_drop_caches & 1) {
54 iterate_supers(drop_pagecache_sb, NULL);
55 count_vm_event(DROP_PAGECACHE);
56 }
57 if (sysctl_drop_caches & 2) {
58 drop_slab();
59 count_vm_event(DROP_SLAB);
60 }
61 if (!stfu) {
62 pr_info("%s (%d): drop_caches: %d\n",
63 current->comm, task_pid_nr(current),
64 sysctl_drop_caches);
65 }
66 stfu |= sysctl_drop_caches & 4;
67 }
68 return 0;
69 }
70