Search code examples
clinuxprocesspid

How do I check if a process is a system process in Linux?


My program can suggest a user to close a specific process if it is consuming too much memory (eg - firefox or chrome).

However, on my system (Ubuntu 16.10 GNOME), some system specific processes like gnome-shell consume too much memory.

My client has no idea if a specific process can be closed or not.

How do I determine if a process is a system process (like gnome-shell) and avoid closing it?

This is how I am obtaining PID and the name of the process of those which consume max memory:

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);
}

Solution

  • IIRC, Ubuntu 16 is already systemd-based. While that does have some issues, at least it cleaned up a lot of existing cruft. Practically speaking, your system processes are managed by the root systemd process. That doesn't mean they're all children of PID 1; systemd has a bit more refined model. In particular, it understands forking daemons (whose parent dies),

    You can get a treelist of systemd services including PID's with systemd-cgls (Control Group LiSt)