简体   繁体   English

C-程序在30秒后不会终止

[英]C- Program won't terminate after 30 seconds

We were asked to prompt the user to enter phrases, and continue asking them until they get the correct phrase needed, for 30 seconds. 我们被要求提示用户输入短语,并继续询问他们,直到他们获得所需的正确短语为止,持续30秒。 Here's what I've come up with: 这是我想出的:

#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;
}

The problem: after 30 seconds, it prints "Time runs out" but won't terminate. 问题:30秒后,它显示“时间用完”,但不会终止。 How do I terminate the program after 30 seconds? 30秒后如何终止程序? Any help? 有什么帮助吗?

Here, you are using fork which creates two separate processes with two different PIDs. 在这里,您使用的是fork,它将使用两个不同的PID创建两个单独的进程。 You are killing child process but parent is still running so program just dont quit. 您正在杀死子进程,但父进程仍在运行,因此程序不会退出。

You could have also used pthread instead of fork with remains in same single process but what ever you are trying to achieve is simple with alarm function. 您也可以在同一单个进程中使用pthread代替fork,但是使用警报功能可以轻松实现。 You dont have to manage any other process. 您不必管理任何其他过程。 Just use alarm. 只需使用警报。

#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;   
} 

Hope it helps !! 希望能帮助到你 !!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM