Book Image

Hands-On System Programming with Go

By : Alex Guerrieri
Book Image

Hands-On System Programming with Go

By: Alex Guerrieri

Overview of this book

System software and applications were largely created using low-level languages such as C or C++. Go is a modern language that combines simplicity, concurrency, and performance, making it a good alternative for building system applications for Linux and macOS. This Go book introduces Unix and systems programming to help you understand the components the OS has to offer, ranging from the kernel API to the filesystem. You'll then familiarize yourself with Go and its specifications. You'll also learn how to optimize input and output operations with files and streams of data, which are useful tools in building pseudo-terminal applications. You'll gain insights into how processes communicate with each other, and learn about processes and daemon control using signals, pipes, and exit codes. This book will also enable you to understand how to use network communication using various protocols, including TCP and HTTP. As you advance, you'll focus on Go's best feature - concurrency, which will help you handle communication with channels and goroutines, other concurrency tools to synchronize shared resources, and the context package to write elegant applications. By the end of this book, you will have learned how to build concurrent system applications using Go
Table of Contents (24 chapters)
Free Chapter
1
Section 1: An Introduction to System Programming and Go
5
Section 2: Advanced File I/O Operations
9
Section 3: Understanding Process Communication
14
Section 4: Deep Dive into Concurrency
19
Section 5: A Guide to Using Reflection and CGO

Writing to file

As we have seen for reading, there are different ways to write files, each one with its own flaws and strengths. In the ioutil package, for instance, we have another function called WriteFile that allows us to execute the whole operation in one line. This includes opening the file, writing its contents, and then closing it.

An example of writing all a file's content at once is shown in the following code:

package main

import (
"fmt"
"io/ioutil"
"os"
)

func main() {
if len(os.Args) != 3 {
fmt.Println("Please specify a path and some content")
return
}
// the second argument, the content, needs to be casted to a byte slice
if err := ioutil.WriteFile(os.Args[1], []byte(os.Args[2]), 0644); err != nil {
fmt.Println("Error:", err)
}
}

This example writes all the content at...