0
votes

Write a C program simulating alarm clock. In the main function, you fork a child process, and the child process sleeps for 5 seconds (the number of seconds is an command line argument, see below for a sample run) , after which the child process sends the signal (SIGALRM) to its parent process. The parent process, after forking the child process, pause, upon receiving the SIGALRM signal, and prints out a message “Ding!”. The following is a sample run

$ ./alarm 5

alarm application starting

waiting for alarm to go off

<5 second pause>

Ding!

done

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


void Dingdong()
{
    printf("Ding!");
    exit(1);
    
}

int main(int argc, char *argv[])
{  
    
    if(argc!=3)

    {
        printf("How much seconds you want to sleep the child process\n");
    }

    int PauseSecond=(argv[1]);
    
    {
        if(fork()==0)
        {
            printf("waiting for alarm to go off\n");  
            printf("%d second pause",PauseSecond);
            sleep(PauseSecond);
            kill(getpid(),SIGALRM);
        }
        else {
            printf("Alarm application starting\n", getpid());  
            signal(SIGALRM,Dingdong);
            printf("done");
        }

    }   
    



}
1

1 Answers

0
votes

Here's what's keeping it from working at all:

  1. int PauseSecond=(argv[1]); That puts the address of the first argument in PauseSecond, which will usually be some really big number. You probably wanted to parse the value of the first argument instead. You need to use something like atoi or strtol on it to do that.
  2. You're calling getpid() after forking, so the child is sending the signal to itself instead of to the parent. Either call getpid() before the fork and save it to a variable, or call getppid() instead.
  3. The parent process is finishing execution and exiting before the child process's sleep ends. You can add the pause() function to the parent process to make it wait for a signal handler to run.
  4. If you want done to print, you can't call exit from the signal handler.

Just fixing the above will get the program sort of working, but there's other things you should consider fixing too:

  1. Since you're not using argv[2] for anything, you should see if argc is 2 instead of 3.
  2. If there aren't enough arguments, you should exit/return instead of continuing and trying to use one that's not there.
  3. You should either put a \n on the end of "%d second pause" or do a manual fflush, or you won't see that until after the sleep.
  4. printf("Alarm application starting\n", getpid()); Your format string won't actually show the result of that getpid().
  5. If you do want to exit from the signal handler, you need to use _Exit, not exit, as the latter isn't async-signal-safe.