Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Go Standard Library Cookbook

You're reading from   Go Standard Library Cookbook Over 120 specific ways to make full use of the standard library components in Golang

Arrow left icon
Product type Paperback
Published in Feb 2018
Publisher Packt
ISBN-13 9781788475273
Length 340 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Radomír Sohlich Radomír Sohlich
Author Profile Icon Radomír Sohlich
Radomír Sohlich
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Interacting with the Environment FREE CHAPTER 2. Strings and Things 3. Dealing with Numbers 4. Once Upon a Time 5. In and Out 6. Discovering the Filesystem 7. Connecting the Network 8. Working with Databases 9. Come to the Server Side 10. Fun with Concurrency 11. Tips and Tricks 12. Other Books You May Enjoy

Calling an external process

The Go binary could also be used as a tool for various utilities and with use of go run as a replacement for the bash script. For these purposes, it is usual that the command-line utilities are called.

In this recipe, the basics of how to execute and handle the child process will be provided.

Getting ready

Test if the following commands work in your Terminal:

  1. Test if the ls (dir for Windows) command exists in your $PATH.
  2. You should be able to execute the ls (dir in Windows) command in your Terminal.

How to do it...

The following steps cover the solution:

  1. Open the console and create the folder chapter01/recipe08.
  2. Navigate to the directory.
  3. Create the run.go file with the following content:
        package main

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

func main() {

prc := exec.Command("ls", "-a")
out := bytes.NewBuffer([]byte{})
prc.Stdout = out
err := prc.Run()
if err != nil {
fmt.Println(err)
}

if prc.ProcessState.Success() {
fmt.Println("Process run successfully with output:\n")
fmt.Println(out.String())
}
}
  1. Run the code by executing go run run.go.
  1. See the output in the Terminal:
  1. Create the start.go file with the following content:
        package main

import (
"fmt"
"os/exec"
)

func main() {

prc := exec.Command("ls", "-a")
err := prc.Start()
if err != nil {
fmt.Println(err)
}

prc.Wait()

if prc.ProcessState.Success() {
fmt.Println("Process run successfully with output:\n")
fmt.Println(out.String())
}
}
  1. Run the code by executing go run start.go.
  2. See the output in Terminal:

How it works...

The Go standard library provides a simple way of calling the external process. This could be done by the Command function of the os/exec package.

The simplest way is to create the Cmd struct and call the Run function. The Run function executes the process and waits until it completes. If the command exited with an error, the err value is not null.

This is more suitable for calling the OS utils and tools, so the program does not hang too long.

The process could be executed asynchronously too. This is done by calling the Start method of the Cmd structure. In this case, the process is executed, but the main goroutine does not wait until it ends. The Wait method could be used to wait until the process ends. After the Wait method finishes, the resources of the process are released.

This approach is more suitable for executing long-running processes and services that the program depends on.

See also

This recipe describes how to simply execute the child process. There are Retrieve child process information and Reading/writing from the child process recipes in this chapter that also provide the steps on how to read from and write to the child process, and get useful information about the process.

You have been reading a chapter from
Go Standard Library Cookbook
Published in: Feb 2018
Publisher: Packt
ISBN-13: 9781788475273
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime