I've updated the question to avoid being accused of posting an XY question.
Previously the question was:
how can I tell when runtime.Goexit has been called on the main goroutine?
I'm trying to write a method that finishes all deferred functions on the main goroutine by calling runtime.Goexit()
and then calls os.Exit()
from a goroutine a spawned before calling this exit method. The problem I have is that I don't know when runtime.Goexit()
has completed. Is there any way I can know when the main goroutine has finished?
UPDATED: Let me elaborate on my use case. Consider this pattern for TestMain
:
func TestMain(m *testing.M) {
db.Create()
defer db.Drop()
os.Exit(m.Run())
}
In this case, the database is never dropped because os.Exit stops the program. My goal was to come up with an alternate
exit function that executes all the deferred functions in TestMain
. Now, I could move everything into another
function like this:
func realTestMain(m *testing.M) int {
db.Create()
defer db.Drop()
return m.Run()
}
func TestMain(m *testing.M) {
os.Exit(realTestMain(m))
}
However, this pattern would have to be enforced across our test suite and is ugly and difficult to remember. I was exploring whether I could have a helper that makes it possible to write my setup/teardown as follows:
func TestMain(m *testing.M) {
db.Create()
defer db.Drop()
helpers.SafeExit(m.Run())
}
With a helper like this, I could write a simple check to ensure that os.Exit never appears in our test suites.