2013-08-15 4 views
4

C에서 기본 셸을 작성하려고합니다. 내가해야 할 일 중 하나는 백그라운드 및 포 그라운드 프로세스를 모두 가질 수 있습니다. Control-C는 포 그라운드 프로세스 (있는 경우)를 종료해야하며 백그라운드 프로세스를 종료해서는 안됩니다.ctrl-c 쉘에서 내 백그라운드 프로세스를 죽이는 경우

포 그라운드 프로세스를 종료시키는 SIGINT 용 신호 처리기를 작성했습니다. 유일한 문제는, 내가 백그라운드 프로세스를 가지고 있다면, 역시 그것을 죽이는 것이다. 내가 이해하는 것으로부터, Control-C가 눌려지면, SIGINT는 다른 프로세스에 큐를 넘겨주고, 핸들을 처리하면 멈추게된다. 쉘이 처리해야하므로 백그라운드 프로세스로 넘어 가지 않아야합니다. 내가 전경 프로세스를 실행하면

pid_t foreground_pid; 

int main(int argc, char *argv[]) { 
    signal(SIGINT, INThandler); 
    char *buf; 

    while(1) { 
     fgets(buf, 128, stdin); 

     */ error checking */ 
     */ split buf into null terminated char* array (arg_array) 
      and count the number of args (num_args) */ 

     handlerCommand(buf, arg_array, num_args); 

     zombieTerminator(); 
} 

void handleCommand(char *command, char **args, int num) { 
    pid_t pid; 

    if ((pid = fork()) < 0) 
     printf("error\n"); 
    else if (pid == 0) { // Child 
     if (!strcmp(args[num-1], "&")) { 
      /* redirect stdin to /dev/null */ 
     } 

     execvp(args[0], args); 
     printf("error\n"); 
     exit(127); 
    } 

    // parent - either wait (foreground) or continue (background) 
    if (!strcmp(args[num-1], "&")) {  
     printf(" [%ld] : %s\n", (long)pid, command); 
    } else { 
     foreground_pid = pid; 
     if ((pid = waitpid(pid, &status, 0)) < 0) 
      fprintf(stderr, "waitpid error\n"); 
    } 

    return; 
} 

/** Terminates any zombie processes that finished in the background */ 
void zombieTerminator(void) { 
    int status; 
    pid_t pid; 

    while ((pid = waitpid(-1, &status, WNOHANG)) > 0) { 
     if (pid != foreground_pid) { 
      printf(" [%ld] exited with status: %d\n", (long)pid, 
        WEXITSTATUS(status)); 
     } 
    } 
} 

/** Handles the control-c signal from the keyboard */ 
void INThandler(int sig) { 
    if (foreground_pid) { 
     kill(foreground_pid, SIGKILL); 
     foreground_pid = 0; 
    } else { 
     printf("\n%s\? ", cwd); 
    } 
    fflush(stdout); 
} 

가 : : 다음 CONTORL-C를 칠 수

sleep(100) 

을하고 종료됩니다

여기 내 코드입니다. 꼭 그래야 해. 그러나 백그라운드 프로세스를 실행하는 경우 :

sleep(100) & 

내가해야하는 것처럼 새로운 프롬프트가 나타납니다. 그러나 컨트롤 -c를 누르면 아무 일도 일어나지 않습니다. 그러나 배경 프로세스가 죽게됩니다.

저는 백그라운드 프로세스가 중지되는 것을 방지하는 방법을 알고 싶습니다. 어떤 아이디어? :)

답변