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

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

Patricia Arquette
Release: 2024-12-12 19:46:15
Original
226 people have browsed it

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

Preventing Ctrl C Interruption of exec.Command Processes

Despite intercepting interrupt calls via signal.Notify, processes started with exec.Command remain susceptible to interruption by Ctrl C. Consider the following demonstration:

package main

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

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

    go func() {
        log.Println("Sleep start")
        cmd := exec.Command("sleep", "60")
        cmd.Run()
        log.Println("Sleep stop")
    }()

    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
}
Copy after login

Pressing Ctrl C during program execution will produce output indicating that the "sleep" command was interrupted, despite the main program not exiting.

Solution: Controlling the Process Group

The interruption arises from the shell signaling the entire process group when Ctrl C is pressed. To isolate the child process from this signal, the command must be started in its own process group. This can be achieved by setting the SysProcAttr.Setpgid and SysProcAttr.Pgid fields before starting the process:

cmd := exec.Command("sleep", "60")
cmd.SysProcAttr = &syscall.SysProcAttr{
    Setpgid: true,
}
Copy after login

By following these steps, the main program can intercept Ctrl C signals without interrupting processes started with exec.Command, ensuring stable process execution.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template