K
K
Kana2015-09-22 04:04:24
go
Kana, 2015-09-22 04:04:24

How to completely kill a child process?

I have the simplest code that just prints numbers in 5/3 seconds.

func main() {
  flag.Parse()
  for i := 0; i < 5; i++ {
    fmt.Println(flag.Arg(0), i)
    time.Sleep(time.Second / 3)
  }
}

In another program, I run "go run first.go %{i}" in a loop, where i is just the index of the loop, and wait for the process to complete. But a second after starting, I kill the process (cmd.Process.Kill()). cmd.Wait() is unblocked, the process is considered killed, the loop starts over. But the numbers continue to be displayed until the end of the program (5/3 seconds). How is it possible that the process seems to be killed, but at the same time continues to work?
Here is the whole code
. There is a suspicion that I kill go, but the child process (the binary compiled by go) goes to init, then finishes its action and dies. Then you need to either build it yourself and run the binary, or learn how to kill go along with the running binary.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg Shevelev, 2015-09-22
@mantyr

go run has some peculiarities, for example, you can run it in the console and forget - it will calmly get rid of the console. Here you have a similar situation. If you want to run some code in a "child" process, then do it explicitly:
1. through fork() - which is not desirable
2. through goroutines
3. ...
But, apparently, you are trying to cross a Golang application with an application in another language (otherwise where such troubles come from). In this case, you need to:
1. teach the application (first.go) to understand the signals of the operating system, for this, study os.Signal and syscall.SIGKILL (in general, read about what signals should be processed when the application terminates) and terminate the application correctly at the right time
2. after all, compile first into a binary, go install first.go and use it already ...
And finally - do not waste resources like that - run another program N times just to count a few similar digits. Form a program more capaciously, send it a bunch of data and get another bunch of results from it at once. Or make a multi-threaded service that accepts requests and issues responses.

S
Sergey N, 2015-09-22
@Albibek

You can ask the kernel to send a SIGHUP to a child process when the parent process dies.
https://stackoverflow.com/questions/284325/how-to-...
But GO doesn't seem to be able to do this without C code yet.
Here is a discussion: https://groups.google.com/forum/#!topic/golang-dev...
If the parent process "dies" in a controlled manner, send a TERM signal (in extreme cases, KILL) to all child processes yourself. That will be the best. If uncontrollable, deal with the parent.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question