Run program in background.

Brian Dessent brian@dessent.net
Tue Oct 5 11:46:00 GMT 2004


Moises Deangelo wrote:

> I did a program in C.
> 
> That program needs to run for a long time, because of this it is ideal
> that he works on background.
> 
> I do not have been managing do that.
> 
>  is there some command? Any lib, anything
> 
> I thank the help.

Your question is not clear.  "Run in the background" can mean lots of
things.

If you just want your program to simply run in the background, launch it
with a "&" at the end of the command from the shell.  However, if it
expects to use stdout, stdin, or stderr, it will stop -- so these must
all be redirected to files or pipes.

This will still leave it attached to the terminal and process group of
the shell, however.  Thus you will not be able to log out of the command
prompt with the background jobs unless you detach them.  To get around
this you can use the "nohup" and/or "setsid" commands when launching it.

If you want your program to daemonize itself (rather than relying on the
user to do it when invoking it), then you will have to read some unix
programming books about the steps involved.  For example, Perl's
Proc::Daemon does the following:

1. Fork a child and exit the parent process.

2. Become a session leader (which detaches the program from the
controlling terminal).

3. Fork another child process and exit first child.  This prevents the
potential of acquiring a controlling terminal.

4. Change the current working directory to "/".

5. Clear the file creation mask.

6. Close all open file descriptors.

As an alternative, under Cygwin you can run your program as a service. 
In this mode you needn't daemonize from within your program, as the
cygrunsrv program launches your program and waits on it.  Thus cygrunsrv
can run any normal program as a service, without needing special code in
the program.  However, you must be mindful of permissions and ownership
as by default you will be running as the SYSTEM account which does not
always have the same access as user accounts.

Brian

--
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple
Problem reports:       http://cygwin.com/problems.html
Documentation:         http://cygwin.com/docs.html
FAQ:                   http://cygwin.com/faq/



More information about the Cygwin mailing list