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 초 후에 어떻게 프로그램을 종료합니까? 어떤 도움이 필요합니까?
'while (1)'에서 멈추었을 때 왜 종료 될 것이라고 기대합니까? – John3136
30 초가 아닙니다. 30 회 반복됩니다. 30 초를 얻으려면 시작 시간에서 현재 시간을 뺀 후 30을 찾으십시오. –
이렇게하면, sleep (30);을 사용하면 루프가 아닌 30 초 동안 sleep 할 수 있습니다. 아이가 깨어 났을 때 부모에게 신호를 보내야합니다. 성공했을 경우 만료 된 것으로보고합니다. 부모는 신호를 처리하고 신호가 수신되면 종료해야합니다. 올바른 입력이 주어지면, 신호를 무시하도록 결정할 수 있으므로 조기에 종료되지 않습니다. 또는, 단일 프로세스의 코드가 SIGALRM을 처리하도록하고,'alarm()'시스템 호출을 사용하여 타임 아웃을 설정할 수 있습니다. 또는 다양한 현대적인 변형 중 하나를 사용하십시오. 그러나'alarm()'이 좋습니다. –