Jin Hui wrote:
> Anyone can give me some ideas about how to write a program (C/C++) in Linux
> which can runs in the background after logoff. Thanks!
If you just want the program to run in the background, use `nohup' and
put an `&' at the end of the command.
If you want to write a daemon process, you should perform the same
steps as the attached program.
--
Glynn Clements <[EMAIL PROTECTED]>
#include <stdio.h> /* for perror */
#include <unistd.h> /* for fork, setsid, chdir, sysconf, close */
#include <sys/stat.h> /* for umask */
int main(void)
{
int n, i;
/* step 1: fork() a child process and exit */
switch (fork())
{
case -1: /* error */
perror("fork");
return 1;
case 0: /* child */
break;
default: /* parent*/
return 0;
}
/* step 2: establish a new session */
if (setsid() < 0)
{
perror("setsid");
return 1;
}
/* step 3: set the cwd */
if (chdir("/") < 0)
{
perror("chdir");
return 1;
}
/* step 4: reset the umask */
umask(0);
/* step 5: close open descriptors */
n = sysconf(_SC_OPEN_MAX);
if (n < 0)
n = 256;
for (i = 0; i < n; i++)
if (close(i) < 0)
perror("close");
/* everything else goes here */
return 0;
}