Home > Backend Development > Golang > Why Does Adding '-o cpu' to My Go `exec.Command` for `top` Cause an Error, and How Can I Fix It?

Why Does Adding '-o cpu' to My Go `exec.Command` for `top` Cause an Error, and How Can I Fix It?

Linda Hamilton
Release: 2024-12-17 04:21:25
Original
718 people have browsed it

Why Does Adding

Using Command Line Arguments with Go

This Go code successfully retrieves details of 10 processes using the "top" command with specific arguments:

package main

import (
    "os/exec"
)

func main() {
    print(top())
}

func top() string {
    app := "/usr/bin/top"

    cmd := exec.Command(app, "-n", "10", "-l", "2")
    out, err := cmd.CombinedOutput()

    if err != nil {
        return err.Error() + " " + string(out)
    }

    value := string(out)
    return value
}
Copy after login

However, an additional "-o cpu" argument causes an error:

cmd := exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2")
Copy after login
Copy after login

In the console, the command "top -o cpu -n 10 -l 2" works as intended. The issue lies in the way the "-o" argument is being passed to the "top" command.

To resolve this, it's necessary to separate the arguments explicitly like:

cmd := exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2")
Copy after login
Copy after login

This ensures that the arguments are passed correctly to the command, allowing it to execute properly.

The above is the detailed content of Why Does Adding '-o cpu' to My Go `exec.Command` for `top` Cause an Error, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template