» Quick Introduction to Go » 3. Advanced » 3.6 OS

OS

Package os provides a platform-independent interface to operating system functionality.

Spawning Processes

You can spawn processes using the os/exec package, which provides a way to start external processes.

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	// Command to execute
	cmd := exec.Command("echo", "Hello, World!")

	// Run the command and capture its output
	output, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Output:", string(output))
}

Signals

You can handle signals using the os/signal package. Signals are a way for an operating system to notify a process that a specific event has occurred, such as a user interrupt (Ctrl+C).

package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	signalChannel := make(chan os.Signal, 1)

	// Notify the signal channel for specified signals
	signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)

	fmt.Println("Application is running. Press Ctrl+C to exit.")

	// Block until a signal is received
	signalReceived := <-signalChannel
	fmt.Printf("Received signal: %v\n", signalReceived)

	fmt.Println("Cleaning up and exiting.")
}

Exit

The os.Exit function allows you to terminate your program with a specific exit code.

package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("Before os.Exit")

	// Exit with a status code of 1
	os.Exit(1)

	// This code will not be executed
	fmt.Println("After os.Exit")
}