Alex Bledea
Alex Bledea

Reputation: 11

Capture the SIGINT signal gracefully during an interactive terminal prompt

It seems that example 3 produces the behavior I'm looking for on Ubuntu, but on Windows it's nowhere close to that. So this question is Windows-specific, and I'd also be interested in what causes this difference in behaviour.

I'm writing an application that will allow inserting debts via the terminal. This is the simplest form which illustrates the insertion process (see full code and my other attempts in the linked gists):

// scanStringUntilValid is a helper provided to get a string input from the
// terminal. It doesn't do any additional logic to simply retrieving the user
// input; it is only provided for consistency.
func scanStringUntilValid(s *bufio.Scanner, prefix string) string {
    fmt.Print(prefix)

    if !s.Scan() {
        return ""
    }
    return s.Text()

}

// scanIntUntilValid is a helper provided to get a float input from the terminal.
// It will prompt the user for a value until the value is a valid floating
// point number.
func scanFloatUntilValid(s *bufio.Scanner, prefix string) float64 {
  // removed code for presentation, full code in gist
}

func CreateDebtPrompter(header string) Debt {
    if header != "" {
        fmt.Println(header)
    }
    s := bufio.NewScanner(os.Stdin)
    debt := Debt{}

    debt.Person = scanStringUntilValid(s, "person: ")
    debt.Amount = scanFloatUntilValid(s, "amount: ")
    debt.Currency = scanStringUntilValid(s, "currency: ")
    debt.Details = scanStringUntilValid(s, "details: ")

    return debt
}

func main() {
    debt := CreateDebtPrompter("")
    fmt.Println("debt created: %s", debt)
    return
}

However, if the user presses Ctrl + C, I want to stop the prompter and display the "exited" message or something. Currently at the moment this happens (I pressed Ctrl + C after writing "abc"), or similar behaviours in my other attempts:

go run main.go

Output:

person: abcamount: Invalid number, please try again.
amount: Invalid number, please try again.
exit status 0xc000013

The main problem is that I wasn't able to make it such that the program completely stops after pressing Ctrl + C without going for the further prompts.

I don't fully understand why, even if I stop the program when the person is written, the code still goes to try and fill the amount. I've tried multiple ways to go about this, but I'm not very familiar with the process that happens to display text in the terminal and interrupts and I think I might be missing some details. I've made other attempts (by looking up ways to solve this problem), and none of them seem to work.

Here are all my attempts:

I also tried some hybrid combinations, but those were my main tracks.

Upvotes: 1

Views: 116

Answers (0)

Related Questions