How to catch CTRL-C in the exec.Command


I’m just a beginner in golang. Please don’t be so hard :slight_smile:

We are using AWS. I’m trying to build a wrapper programm to call “aws ssm session-start --target [instance-id]”. Our aim is to use “aws ssm” to get interactive shell on the instance.

I have written a function:

func commandRun(instanceId string) error {
  cmd := exec.Command("aws", "ssm", "start-session", "--target", instanceId)
  cmd.Stderr = os.Stderr
  cmd.Stdout = os.Stdout
  cmd.Stdin = os.Stdin

  err := cmd.Run()

  if err != nil{
  return nil

Using it I can connect to a server, get a shell and run some commands. No problem. But. If I’m using some commands like “top”, that has to be exit with “Ctrl-C”, there is some problem. With “Ctrl-C” I’m leaving not only “top” but whole go-program. Therefore I thought I could catch “Ctrl-C” and ignore it for the go-wrapper itself. I red normally for such problem you would use some goroutine to run cmd in it and some channel to catch “Ctrl-C”. For our purpose I can’t use such solution because if cmd.Run() would run in goroutine we wouldn’t get an interactive shell to see.

Do you have some ideas to solve such problem?

Thank you very much in advance!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.