johnpoint

johnpoint

(。・∀・)ノ゙嗨
github

Linux Process Information Formatting

It's 2021, and I took a look at my server panel and found that it's still in that semi-finished state... So I spent the past three days making some changes to the code and adding the v2 API interface. This interface mainly uses Websockets for communication. Although the server's load is not very high, using polling for data updates not only results in a bunch of requests, but also puts some strain on my weak computer. But that's not the topic of this article, I'll write another article about it another day.

Process viewing was actually one of the features I wanted to implement in the panel a long time ago, but I was limited because I couldn't find any ready-made third-party or official Go libraries. So I put it on hold (and ended up putting it off for almost a year). Coincidentally, these past few days I was working on the panel's code, so I decided to just go ahead and implement it.

Since there are no libraries for process viewing, I can only use system commands to view processes. Usually, I use ps -aux to view processes, but for the panel, the output data is a bit too much and a bit messy (by messy, I mean the output data is not in a computer-friendly format). So after looking at various commands from online users, I pieced together a command that uses ps axc -o pid,user,stat,pcpu,pmem,command --sort -pcpu --no-header | sed 's/\ \+/\ /g'. The resulting data doesn't have a header and consecutive spaces are replaced with a single space. I think this is enough, the rest can be handled by the frontend.

Here's a snippet of the frontend code:

let ps = server.Ps.split('\n');
ps.forEach(item => {
    if (item.split(" ").length > 3) {
        item = item.split(" ");
        if (item[0] === "") {
            item = item.slice(1, item.length);
        }
        let i = {
            PID: item[0],
            User: item[1],
            State: item[2],
            Pcpu: item[3],
            Pmem: item[4],
            Command: item.slice(5, item.length).toString().replaceAll(",", " "),
        };
        this.psData.push(i);
    }
});

The end result is pretty good~

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.