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

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

DDD
DDDOriginal
2024-12-11 02:26:11316browse

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

Preventing Ctrl C From Disrupting exec.Command in Golang

Interruptions from Ctrl C can be encountered when utilizing exec.Command to initiate processes, even when interrupt calls are intercepted via signal.Notify. This issue arises because the shell transmits signals to the entire process group upon receipt of Ctrl C. As a result, child processes initiated with exec.Command are also affected.

To mitigate this problem and prevent Ctrl C from interrupting the child processes, it is necessary to establish the command with its own process group before commencing execution. This can be achieved by employing the SysProcAttr, Setpgid, and Pgid fields of the syscall.SysProcAttr structure.

Here's an amended example that incorporates this approach:

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("Received Ctrl + C")
    }()

    <-doneChannel
}

With this modification, when Ctrl C is pressed while the program is in execution, the following output is produced:

2015/10/16 10:05:50 Sleep start
^C2015/10/16 10:05:52 Received Ctrl + C

The sleep command continues to run successfully, demonstrating the prevention of interruption through Ctrl C.

The above is the detailed content of How Can I 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