Go by Example: Spawning Processes

In Go, you can spawn a new process by using the os/exec package. Here’s an example of how to run the ls command and retrieve its output:

package main

import (
	"bufio"
	"fmt"
	"os/exec"
)

func main() {
	// Run the ls command
	cmd := exec.Command("ls")

	// Get the standard output of the command
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Println(err)
		return
	}

	// Start the command
	if err := cmd.Start(); err != nil {
		fmt.Println(err)
		return
	}

	// Read the standard output of the command
	scanner := bufio.NewScanner(stdout)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		fmt.Println(err)
		return
	}

	// Wait for the command to finish
	if err := cmd.Wait(); err != nil {
		fmt.Println(err)
		return
	}
}

This program runs the ls command and retrieves its output using the StdoutPipe method of the exec.Cmd struct. The standard output of the command is read using a bufio.Scanner and printed to the console. Finally, the program waits for the command to finish using the Wait method.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *