2009-02-27 61 views
3

连续运行应用程序的最明智方式是什么,以便它在触底之后不会退出?相反,它会从主体的顶部重新开始,并且只有在命令时才退出。 (这是用C语言编写的)连续运行应用程序

回答

10

你应该总是有一些干净地退出的方式。我建议将代码移到另一个返回一个标志来说明是否退出的函数。

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; 
} 
2
while (true) 
{ 
.... 
} 

为了详细阐述一下,你需要在该循环中加入一些东西,让用户可以重复操作。无论是读按键还是根据按键执行操作,或者从套接字读取数据并发回响应。

4

大多数不经历的应用程序进入某种事件处理循环,允许进行事件驱动的编程。例如,在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 DaemonsWindows Services

1

有许多方法可以“命令”您的应用程序退出(例如全局退出标志或返回代码)。有些已经涉及到使用退出代码,所以我会提出一个使用退出标志对现有程序进行的简单修改。

让我们假设你的程序执行系统调用输出目录列表(完整目录或单个文件):

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()
  • 添加新的exitFlag
  • 添加新的main()不断呼叫oldMain()直到退出标记。
  • 更改oldMain()在某个点发出信号退出。

这给了下面的代码:

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; 
} 
相关问题