#make go program restart itself

34 messages · Page 1 of 1 (latest)

scarlet delta
#

use signal package

#

yes, when you press ctrl+c on the terminal, your shell send sigterm to your program.
if your program didn't not handle it, the kernel will take over and terminate your app

pearl plume
#

https://pkg.go.dev/os/signal
It's built in.
You have lots of options in how you use it.
You can restart from any point in your program based on how you process a signal.
The details depend largely on your application.

#

Another thing that you may be looking for is systemd, but that's not a Go thing. Depends on your deployment environment

scarlet delta
#

yes. but also it'll take hours to explain what os signal is.

pearl plume
#

Your best option is to read the package documentation and come back with questions. We may not have answers but we can also point you towards other resources.

hasty rover
#

I'd ask: Do you want to restart your whole application or do you want to start executing the same application code from the beginning

pearl plume
#

True, depending on that answer signal or systemd may be overkill.

hasty rover
#

first use case would be something like an in place update of your app.

#

signals

pearl plume
#

I mean.
You can just... Call main, right?

#

I've never tried it.

#

It's a function though

#

Why not?

scarlet delta
#

isn't it recursive?

pearl plume
#

This is probably not a production safe option.

#

But I am interested in the outcome.

hasty rover
#

Second question: what application do you want to restart. Your parent or some child process you spawned?

scarlet delta
hasty rover
#

that will most likely lead to a stack overflow?

pearl plume
#

I wouldn't call main inside main.
It may work now but I'd be concerned it won't scale, as a pattern.
But whether you need it to scale is a function of what you're doing with your project.

hasty rover
#

with enough restarts?

pearl plume
#

Depends on the control flow

#

But yes. Running out of stack space is one issue.

hasty rover
#

you would need to put your whole main() code in a separate function

#

and put a loop around it

scarlet delta
pearl plume
#

Do that.

hasty rover
#

but calling main() will allocate new stack memory on every restart

#

leaking memory

pearl plume
#

Yep. It won't scale as well as that loop will.

#

Loop gives infinite restarts. 😄

hasty rover
#

mark as solved