The result of Top command implemented by go os/exec behave inconsistently across different golang versions

package main
  
import (
        "fmt"
        "os/exec"
        "strconv"
        "strings"
)

func  MyTop(topNum uint, args ...string) (out []byte, err error) {
        lineNumStr := strconv.FormatUint(uint64(topNum), 10)
        shCmd := []string{"top", "-n", "1", "-b"}
        shCmd = append(shCmd, args...)
        shCmd = append(shCmd, "|", "head", "-n", lineNumStr)

        cmd := exec.Command("bash", "-c", strings.Join(shCmd, " "))
        buf, err := cmd.Output()
        return buf, err
}

func main() {
   buf_mem, _ := MyTop(20, "-o", "%MEM")
   fmt.Printf("top memeory >\n %s", buf_mem)
    return
}

the output is different in go1.15.7 and go1.19.10:

what happened here in go1.19.10?

I doubt go version has anything to do with this. What happens on that second OS (node1 not node-77) when you just run top in a shell? You could also rule out the go version by compiling on an OS with go version 1.15.7 and then using that binary on node1 to see if the output is different (I’m assuming you’re just using go run . here, not a binary).

the results were the same when I just run ‘top -n 1 -b -o %MEM’ commnad in a shell on both host(node1, node-77)

I compiled a binary on a host with go version 1.19.10(node 1), and run it on node-77, which go version is go1.15.7, and the result is that it behaved normal,

Well, the version of go that is installed on node-77 has no bearing on how the binary performs, so that points to the command itself. Check your .bashrc for settings? I’m not super familiar with top or else I might have more specific troubleshooting steps there. Can you just specify the columns in the output?

Well, my .bashrc is quite simple, nothing special in it, they are all default settings.

Can you just specify the columns in the output?

sure, I will have a try

It seems top in other environment is simply configured with COMMAND field turned off. See man 1 top for configuration options, especially personal configuration files section.

I don’t think it’s about command configuration options. What I run in different machines is the same, that is “top -n 1 -b -o %MEM”.

I finally figured it out that it’s $HOME/.toprc configuration file’s fault. I should delete it.
Thanks @Dean_Davidson and @dunric :laughing:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.