如何在这个简单的C shell中设置超时?

问题描述:

现在的代码会生成一条命令并执行指定的次数。我是C新手,对语法不太了解。基本上,我想以某种方式为我正在制定的不同流程设置最大持续时间,并在流程达到该持续时间时终止流程。如何在这个简单的C shell中设置超时?

#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <string.h> 
#include <signal.h> 
#include <time.h> 

#define TRUE 1 
#define FALSE 0 

// tokenize the command string into arguments - do not modify 
void readCmdTokens(char* cmd, char** cmdTokens) { 
    cmd[strlen(cmd) - 1] = '\0'; // drop trailing newline 
    int i = 0; 
    cmdTokens[i] = strtok(cmd, " "); // tokenize on spaces 
    while (cmdTokens[i++] && i < sizeof(cmdTokens)) { 
    cmdTokens[i] = strtok(NULL, " "); 
    } 
} 

// read one character of input, then discard up to the newline - do not modify 
char readChar() { 
    char c = getchar(); 
    while (getchar() != '\n'); 
    return c; 
} 

// main method - program entry point 
int main() { 
    char cmd[81]; // array of chars (a string) 
    char* cmdTokens[20]; // array of strings 
    int count; // number of times to execute command 
    int parallel; // whether to run in parallel or sequentially 
    int timeout; // max seconds to run set of commands (parallel) or each command (sequentially) 

    while (TRUE) { // main shell input loop 

    // begin parsing code - do not modify 
    printf("clonsh> "); 
    fgets(cmd, sizeof(cmd), stdin); 
    if (cmd[0] == '\n') continue; 
    readCmdTokens(cmd, cmdTokens); 
    do { 
     printf(" count> "); 
     count = readChar() - '0'; 
    } 
    while (count <= 0 || count > 9); 
    printf(" [p]arallel or [s]equential> "); 
    parallel = (readChar() == 'p') ? TRUE : FALSE; 
    do { 
     printf(" timeout> "); 
     timeout = readChar() - '0'; 
    }while (timeout < 0 || timeout > 9); 
    // end parsing code 


    //////////////////////////////////////////////////////// 
    //             // 
    // TODO: use cmdTokens, count, parallel, and timeout // 
    // to implement the rest of closh      // 
    //             // 
    // ///////////////////////////////////////////////////// 



    int pid; 
    //clock_t myClock; 
    for (int i=0;i<count; i++) 
    { 

     pid = fork(); 

     if (pid == 0) 
     { 
      printf("My process ID : %d\n", getpid()); 
      //printf("My parent process ID : %d\n", getppid()); 
      execvp(cmdTokens[0], cmdTokens); 

     } 

     /*myClock=clock(); 
     if (myClock>9000000) 
      kill (pid, SIGKILL);*/ 

    } 



return 0; 

    } 


} 
+0

虽然不是一个特定的重复,但这个问题更详细地询问你要完成什么:[Waitpid等同于超时?](http://*.com/questions/282176/waitpid-equivalent-with-超时) – 2014-10-17 03:22:53

主要有两种解决方案:

  1. 每个分叉过程中的一些延迟后自杀身亡。这在alarm(sec)的帮助下很容易做到。这种呼叫将让系统在指定的延迟后发送SIGALRM信号给呼叫进程。
  2. 父进程控制其子代的生命周期。主要问题是避免繁忙的等待。第二个问题是难以管理不同的定时器。一个基本的解决方案是有一个与延迟有关的儿童表。然后你可以使用alarm()来捕获和超时事件kill()这个过程,然后为续集设置一个新的alarm() ......在呼叫警报之后,父进程可以悄悄地去睡一个wait()的调用。如果这样的通话成功结束,您只需从表中删除进程。
+0

谢谢!这使我朝着正确的方向发展 – MWeezy 2014-10-17 12:18:52