To wait for an external command or process to finish using the os
package in Go, you can use the Wait
method of the os.Process
type. Here's an example:
package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("ls") // Replace "ls" with your command
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Waiting for command to finish...")
err = cmd.Wait()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Command finished with exit code %v\n", cmd.ProcessState.ExitCode())
}
In this example, we create an exec.Cmd
object with the command you want to execute using exec.Command
. Then, we call cmd.Start()
to start the command. Next, we wait for the command to finish using cmd.Wait()
.
After the cmd.Wait()
call returns, you can check the exit code of the command using cmd.ProcessState.ExitCode()
. You can use this exit code to determine if the command finished successfully or if there was an error.
Remember to replace "ls"
in exec.Command("ls")
with the command you want to execute.