func init() {
go loop()
}
func loop() {
defer final()
for {
send()
sleep(2)
}
}
func final() { write()}
--
See https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/PCVy2dGGai0
For your problem, you need signal handling:
func signalCatcher() {
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT)
<-ch
log.Println("CTRL-C; exiting")
os.Exit(0)
}
func main() {
go signalCatcher()
...
}
package mainimport ("fmt""os""os/signal""syscall")
func signalCatcher() {ch := make(chan os.Signal)signal.Notify(ch, syscall.SIGINT)<-ch
fmt.Println("CTRL-C; exiting")os.Exit(0)}func main() {go signalCatcher() // Does not prints "CTRL-C; exiting"// signalCatcher() // prints "CTRL-C; exiting" but doesn't run the code belowi := 0for {println(i)i++}}
-Simon Watt
package main
import (
"fmt"
"os"
"os/signal"
"runtime"
"syscall"
)
func signalCatcher() {
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT)
<-ch
fmt.Println("CTRL-C; exiting")
os.Exit(0)
}
func main() {
go signalCatcher()
I'm guessing you meant to put your call to runtime.GOMAXPROCS(2) outside of the for loop.
package main
import (
"fmt"
"os"
"os/signal"
"runtime"
"syscall"
"time"
)
func signalCatcher() {
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT)
<-ch
fmt.Println("CTRL-C; exiting")
os.Exit(0)
}
func main() {
go signalCatcher()
i := 0
runtime.Gosched()
for {
println(i)
i++
sleep(1)
}
}
func sleep(sec time.Duration) {
time.Sleep(time.Second * sec)
}
This call will go away when the scheduler improves.And Gosched() works, I don't understand why it does. Is there a reason not to use it?We have init() to initialize function and I need a finalize function also.
I created the code below, but it doesn't work when the code gets terminated with Ctrl-cI need that to work! Any solutions?This is for a mail script:func init() {go loop()}func loop() {defer final()for {send()sleep(2)}}func final() {write()}
--