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

前端 未结 20 1734
难免孤独
难免孤独 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:58

    Here is some pseudocode for Linux/UNIX:

    initialization_code()
    if(failure) exit(1)
    if( fork() > 0 ) exit(0)
    setsid()
    setup_signal_handlers()
    for(fd=0; fd

    And congratulations, your program continues as an independent "daemonized" process without a controlling TTY and without any standard input or output.

    Now, in Windows you simply build your program as a Win32 application with WinMain() instead of main(), and it runs without a console automatically. If you want to run as a service, you'll have to look that up because I've never written one and I don't really know how they work.

提交回复
热议问题