【发布时间】:2017-01-23 13:24:06
【问题描述】:
如果某个特定进程消耗过多内存(例如 - firefox 或 chrome),我的程序会建议用户关闭它。
但是,在我的系统 (Ubuntu 16.10 GNOME) 上,某些系统特定进程(如 gnome-shell)会消耗太多内存。
我的客户不知道是否可以关闭特定进程。
如何判断一个进程是否为系统进程(如 gnome-shell)并避免关闭它?
这就是我获取 PID 和消耗最大内存的进程名称的方式:
FILE * pipe = popen("ps aux --sort=-%mem | awk 'NR<=2{print $2}'", "r");
if(pipe)
{
char line[line_buf];
while(fgets(line, sizeof line, pipe) != NULL)
{
if(sscanf(line, "%d", &_pid) == 1)
{
_mem->pid = _pid;
}
}
}
pclose(pipe);
if(_mem->pid != 0) {
char command[128], pidname[40];
snprintf(command, sizeof command, "cat /proc/%d%s", _pid, "/comm");
FILE * _pipe = popen(command, "r");
if(pipe)
{
char line[line_buf];
fgets(line, sizeof line, _pipe);
sscanf(line, "%s\n", pidname);
}
pclose(_pipe);
strcpy(_mem->pname, pidname);
}
【问题讨论】:
-
像 gnome-shell 这样的“系统进程”和任何其他用户进程之间没有简单的区别。如果 linux 内存不足,oom-killer 将尝试自己做出合格的选择并终止进程,直到 oom-condition 结束。这并不总是完美的,但在许多情况下它做得很好!
-
所以基本上我应该把工作留给操作系统本身?
-
就linux而言,我建议这样做
-
另一种选择可能是使用
ps ux仅列出用户拥有的进程。