Running a rust program in the background

I'm looking for an easy way to take any given rust program and have it run in the background exactly as if an & was added to the program.

In affect I want to have the code act as the it were executed like this:

cargo run &

I would like the bash shell prompt appear and any output from the child process launched show up.

All examples I have found do not end up with the bash shell running.

My example is to launch a simple REST webserver.

Has anyone done this before?

1 Like

The term for such a program is a daemon.

This crate exists, but if you want the output to appear on standard out, you'll have to do something like opening /dev/stdout as a file (as it redirects to /dev/null by default, and the only override is to pass in a File).

Incidentally, when you run a daemon or run a background process, you're returned to whatever shell you were already running.

2 Likes

Thank you! I had looked over several other options that I found on stackoverflow but this one looks better than any of them.

So far this solution is great.

Although I feel like I'm missing something obvious.

It writes the pid to a file, but do you have any idea how to find what the pid is from the parent program?

I could obviously read the file but that would seem like a waste. It seems the start method should return a pid, or the structure would have a method that would return the pid.

I believe (but have not confirmed) that you could do something like

    let daemonize = Daemonize::new()
        .this_option()
        .that_option()
        .privileged_action(libc::get_pid);

    let pid = daemonize.start().unwrap();

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.