How can a C/C++ program put itself into background?

前端 未结 20 1714
难免孤独
难免孤独 2020-12-09 18:16

What\'s the best way for a running C or C++ program that\'s been launched from the command line to put itself into the background, equivalent to if the user had launched fro

20条回答
  •  失恋的感觉
    2020-12-09 18:54

    The simplest form of backgrounding is:

    if (fork() != 0) exit(0);
    

    In Unix, if you want to background an disassociate from the tty completely, you would do:

    1. Close all descriptors which may access a tty (usually 0, 1, and 2).
    2. if (fork() != 0) exit(0);
    3. setpgroup(0,getpid()); /* Might be necessary to prevent a SIGHUP on shell exit. */
    4. signal(SIGHUP,SIG_IGN); /* just in case, same as using nohup to launch program. */
    5. fd=open("/dev/tty",O_RDWR);
    6. ioctl(fd,TIOCNOTTY,0); /* Disassociates from the terminal */
    7. close(fd);
    8. if (fork() != 0) exit(0); /* just for good measure */

    That should fully daemonize your program.

提交回复
热议问题