golang

OS Exit Golang

An exit code or an exit status is a number returned by a program to indicate whether a program has successfully executed or encountered an error.

Typically, an exit code of 0 means that the program executes successfully. Any other numerical value between 1 and 125 (golang) shows the program encountered an error.

We can use the os package to exit a function with a specific exit code in Go. Follow this short to understand how to work with the exit() function.

The Basics – Exit()

The exit method from the os package helps us terminate a program with a specific error code. The syntax is as shown:

func Exit(code int)

The function takes an exit code between 0 and 125 as the argument.

The program will die instantly if it encounters the exit() function. This means that delayed functions will not run.

Example – Error

In the example below, the program terminates the program after the exit() function.

package main
import (
    "fmt"
    "os"
)
funcmain() {
    fmt.Println("I run")
    os.Exit(5)
    fmt.Println("I never run")
}

If we run the code above, we will execute the code before the exit() method. The program then quits and prints an exit message as:

$ go run exit.go
I run
exit status 5

As mentioned, an error code above 0 indicates an error. However, keep in mind reserved exit codes as shown in the resource below:

https://tldp.org/LDP/abs/html/exitcodes.html

Example – Success

To exit a program without an error, you can set the exit code of the program to 0, as shown in the example below:

package main
import (
    "fmt"
    "os"
)
funcmain() {
    fmt.Println("I run")
    os.Exit(0)
    fmt.Println("I never run")
}

Regardless of the error code, any code after the exit() method does not run.

Conclusion

This short guide covered how to use the exit() method from the os package. Using this method, you can axe 😊 a program with an exit status.

Thanks for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list