2016-11-10 2 views
2

30 초 동안 올바른 구를 얻을 때까지 구를 입력하라는 메시지가 표시됩니다.30 초 후에 C- 프로그램이 종료되지 않습니다.

#include <sys/types.h> 
#include <unistd.h> 
#include <signal.h> 
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

void childprocess(void) 
{ 
    int start = 30; 
    do 
    { 
     start--; 
     sleep(1); 
    } while (start >= 0); 
    printf("Time ran out!\n"); 
    exit(EXIT_SUCCESS); 
} 

int main(void) 
{ 
    pid_tiChildID;/* Holds PID of current child */ 
    char word[100] = "cat"; 
    char input[100]; 
    int length; 
    iChildID = fork(); 
    if (0 > iChildID) 
    { 
     perror(NULL); 
     return 1; 
    } 
    else if (0 == iChildID) 
    { 
     childprocess(); 
     return 0; 
    } 
    /* Parent process */ 
    while (1) 
    { 
     fgets(input, sizeof(input), stdin); 
     length = strlen(input); 
     if (input[length - 1] == '\n') 
     { 
      --length; 
      input[length] = '\0'; 
     } 
     if (strcmp(word, input) == 0) 
      break; 
     printf("Try again\n"); 
    } 
    kill(iChildID, SIGUSR1);/* terminate repeating message */ 
    printf("Finally!\n"); 
    return 0; 
} 

문제 : : 여기로 왔어요 무슨 30 초 후에, 그것은 "시간이 다 떨어지기"하지만 종료되지 않습니다 인쇄합니다. 30 초 후에 어떻게 프로그램을 종료합니까? 어떤 도움이 필요합니까?

+1

'while (1)'에서 멈추었을 때 왜 종료 될 것이라고 기대합니까? – John3136

+0

30 초가 아닙니다. 30 회 반복됩니다. 30 초를 얻으려면 시작 시간에서 현재 시간을 뺀 후 30을 찾으십시오. –

+0

이렇게하면, sleep (30);을 사용하면 루프가 아닌 30 초 동안 sleep 할 수 있습니다. 아이가 깨어 났을 때 부모에게 신호를 보내야합니다. 성공했을 경우 만료 된 것으로보고합니다. 부모는 신호를 처리하고 신호가 수신되면 종료해야합니다. 올바른 입력이 주어지면, 신호를 무시하도록 결정할 수 있으므로 조기에 종료되지 않습니다. 또는, 단일 프로세스의 코드가 SIGALRM을 처리하도록하고,'alarm()'시스템 호출을 사용하여 타임 아웃을 설정할 수 있습니다. 또는 다양한 현대적인 변형 중 하나를 사용하십시오. 그러나'alarm()'이 좋습니다. –

답변

3

여기서 두 개의 서로 다른 PID로 두 개의 개별 프로세스를 만드는 fork를 사용하고 있습니다. 당신은 자식 프로세스를 죽이고 있지만 부모는 아직 실행 중이므로 프로그램이 종료되지 않습니다.

포크 대신 pthread를 사용할 수도 있지만 동일한 단일 프로세스에서 나머지는 유지하려고하지만 알람 기능을 사용하면 간단하게 달성하려고하는 것이 있습니다. 다른 프로세스를 관리 할 필요가 없습니다. 그냥 알람을 사용하십시오.

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

static void ALARMhandler(int sig) 
{ 
    printf("Time ran out!\n"); 
    exit(EXIT_SUCCESS); 
} 

int main(void) 
{ 
    char word[100] = "cat"; 
    char input[100]; 
    size_t length; 

    signal(SIGALRM, ALARMhandler); 
    alarm(30); 

    while(1) { 
     fgets(input, sizeof(input),stdin); 
     length = strlen(input); 
     if(input[length-1] == '\n') { 
      --length; 
      input[length] = '\0'; 
     }   
     if (strcmp(word,input) == 0) 
      break; 
     printf("Try again\n"); 
    } 

    /* terminate repeating message */ 
    printf("Finally!\n"); 
    return 0; 
} 

희망 하시겠습니까?

관련 문제