Search code examples
linuxgoexec

Getting incorrect results while running linux top command in golang using exec


I am trying to get the top running processes in golang, for which I am running linux top command using golang "os/exec" package but getting discrepancy in the Process name.

Process name is truncated and a "+" suffix is added to the name in golang output. But when running the same command in terminal, it is showing the full process name.

Command: top -b -n 1

I am running the following code:

cmd := exec.Command("top","-b","-n","1")
out, err := cmd.Output()
if err != nil {
    fmt.Println("Error in running command ", err)
}
fmt.Println(string(out))

Expected result: Top running processes with full command name, e.g row:

 137295 root      20   0       0      0      0 I   0.0   0.0   0:00.00 kworker/u1:1-writeback

Result returned in go output row:

 137295 root      20   0       0      0      0 I   0.0   0.0   0:00.00 kworker+

Notice the discrepancy in command name kworker/u4:2-writeback and kworker+


Solution

  • As Shawn said, top will assume a default width when running from a different process. Explicitly setting the width in the top command worked for me.

    cmd := exec.Command("top", "-b", "-n", "1", "-w", "100")