Anita Dick
Anita Dick

Reputation: 33

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. 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. How do I terminate the program after 30 seconds? Any help?

Upvotes: 2

Views: 734

Answers (1)

Kalrav J Parsana
Kalrav J Parsana

Reputation: 161

Here, you are using fork which creates two separate processes with two different PIDs. 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. 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 !!

Upvotes: 3

Related Questions