Run the application continuously

What is the smartest way to run an application all the time so that it doesn't exit after it hits the bottom? Instead, it starts again from the top of the main one and is only issued upon command. (This is in C)

+3
source share
4 answers

You should always have some way of failing. I would suggest moving the code to another function that returns a flag to say whether to exit or not.

int main(int argc, char*argv[])
{

     // param parsing, init code

     while (DoStuff());

    // cleanup code
    return 0;
 }

 int DoStuff(void)
 {
     // code that you would have had in main

     if (we_should_exit)
         return 0;

     return 1;
 }
+10
source

Most applications that do not get into the system enter into some kind of event processing loop that allows event driven programming.

Win32 , , WinMain, , WM_QUIT, . :

// ...meanwhile, somewhere inside WinMain()
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
     TranslateMessage(&msg);
     DispatchMessage(&msg);
}

SDL, SDL, , , Esc. :

bool done = false;
while (!done)
{
    SDL_Event event;
    while (SDL_PollEvent(&event))
    {
        switch (event.type)
        {
            case SDL_QUIT:
                done = true;
                break;
            case SDL_KEYDOWN:
                if (event.key.keysym.sym == SDLK_ESCAPE)
                {
                    done = true;
                }
                break;
        }
    }
}

Unix Daemons Windows .

+4
while (true)
{
....
}

, - , . , .

+2

"" (, ). , , , .

, ( ):

int main (int argCount, char *argValue[]) {
    char *cmdLine;
    if (argCount < 2) {
        system ("ls");
    } else {
        cmdLine = malloc (strlen (argValue[1]) + 4);
        sprintf (cmdLine, "ls %s", argValue[1]);
        system (cmdLine);
    }
}

. :

  • main() oldMain().
  • Add a new one exitFlag.
  • Add a new one main()for continuous calling oldMain()until a flag is checked.
  • Change oldMain()to a signal output at some point.

This gives the following code:

static int exitFlag = 0;

int main (int argCount, char *argValue[]) {
    int retVal = 0;

    while (!exitFlag) {
        retVal = oldMain (argCount, argValue);
    }

    return retVal;
}

static int oldMain (int argCount, char *argValue[]) {
    char *cmdLine;
    if (argCount < 2) {
        system ("ls");
    } else {
        cmdLine = malloc (strlen (argValue[1]) + 4);
        sprintf (cmdLine, "ls %s", argValue[1]);
        system (cmdLine);
    }

    if (someCondition)
        exitFlag = 1;
}
+1
source

Source: https://habr.com/ru/post/1703935/


All Articles