Home >Backend Development >Golang >How to Prevent Ctrl C from Interrupting exec.Command in Go?

How to Prevent Ctrl C from Interrupting exec.Command in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 20:46:13780browse

How to Prevent Ctrl C from Interrupting exec.Command in Go?

Preventing Ctrl C from Interrupting exec.Command in Golang

When executing external processes using exec.Command, you may encounter an issue where the processes are interrupted by Ctrl C even if you've intercepted the interrupt signal.

This behavior occurs because the shell signals the entire process group when Ctrl C is pressed. The parent process receives the signal and forwards it to all child processes, causing them to be interrupted.

To prevent this, you can use syscall.SysProcAttr to start the command in its own process group. By setting the Setpgid field to true, you create a new process group for the command, separating it from the parent process.

Here's how to modify your example using syscall.SysProcAttr:

package main

import (
    "log"
    "os"
    "os/exec"
    "os/signal"
    "syscall"
)

func sleep() {
    log.Println("Sleep start")
    cmd := exec.Command("sleep", "60")
    cmd.SysProcAttr = &syscall.SysProcAttr{
        Setpgid: true,
    }
    cmd.Run()
    log.Println("Sleep stop")
}

func main() {
    var doneChannel = make(chan bool)

    go sleep()

    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)
    signal.Notify(c, syscall.SIGTERM)
    go func() {
        <-c
        log.Println("Receved Ctrl + C")
    }()

    <-doneChannel
}

Now, when you press Ctrl C during execution, only the main program will receive the signal. The sleep command will continue running until its completion time of 60 seconds. This ensures that the process is not interrupted unexpectedly.

The above is the detailed content of How to Prevent Ctrl C from Interrupting exec.Command in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn