user1166981
user1166981

Reputation: 1746

Is it possible to run a program from terminal and have it continue to run after you close the terminal?

I have written a program which I run after connecting to the box over SSH. It has some user interaction such as selecting options after being prompted, and usually I wait for the processes it carries out to finish before logging out which closes the terminal and ends the program. But now the process is quite lengthy and I don't want to wait whilst being logged in, so how could I implement a workaround for this in C please?

Upvotes: 5

Views: 3587

Answers (6)

Dave
Dave

Reputation: 11162

The actual C code to background a process is trivial:

//do interactive stuff...  
if(fork())
     exit(0);
//cool, I've been daemonized.

If you know the code will never wind up on a non-linux-or-BSD machine, you could even use daemon()

//interactive...
daemon(0, 0);
//background...

Upvotes: 0

BRPocock
BRPocock

Reputation: 13914

There are many options :-) TIMTOWTDI… However, for your purposes, you might look into running a command-line utility such as dtach or GNU screen.

If you actually want to implement something in C, you could re-invent that wheel, but from your description of the problem, I doubt it should be necessary…

Upvotes: 0

FatalError
FatalError

Reputation: 54551

The traditional way to do this is using the nohup(1) command:

nohup mycmd < /dev/null >& output.log &

Of course if you don't care about the output you can send it to /dev/null too, or you could take input from a file if you wanted.

Doing it this way will protect your process from a SIGHUP that would normally cause it to exit. You'll also want to redirect stdin/stdout/stderr like above, as you'll be ending your ssh session.

Syntax shown above is for bash.

Upvotes: 2

Joni
Joni

Reputation: 111259

The process is sent the HUP signal when the shell exits. All you have to do is install a signal handler that ignores SIGHUP.

Or just run the program using nohup.

Upvotes: 3

mantrid
mantrid

Reputation: 2840

you can use screen command. here is a tutorial. note you might need to install it to your systems.

Upvotes: 1

Seidr
Seidr

Reputation: 4936

You can run a program in the background by following the command with "&"

wget -m www.google.com &

Or, you could use the "screen" program, that allows you to attach-deattach sessions

screen wget -m www.google.com

(PRESS CTRL+D)

screen -r (TO RE ATTACH)

http://linux.die.net/man/1/screen

Upvotes: 7

Related Questions