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

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

    So, as you say, just fork()ing will not do the trick. What you must do is fork() and then re-exec(), as this code sample does:

    #include stdio.h>
    #include 
    #include 
    
    #include 
    
    int main(int argc, char **argv)
    {
        int i, j;
    
        for (i=1; i

    The loop is to check for a --daemon argument, and if it is present, remove it before re-execing so an infinite loop is avoided.

    I don't think this will work if the binary is put into the path because argv[0] is not necessarily a full path, so it will need to be modified.

提交回复
热议问题