Sunday, April 22, 2018

Catching Signal, Child to Parent

Now, I am sending a signal(Ctrl+C) from Child to Parent, using 'kill' command. 'Kill' needs pid of the process & Signal to be sent.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

// Function telling what to do when we catch CTRL+C
void catch_signal (int sig_num)
{
 printf("SIGNAL FUNCTION>> Caught the signal %d by process with PID=%d\n",sig_num,getpid());
 fflush(stdout);
}

int main()
{
 pid_t child_pid;
 int status;

 child_pid=fork();
 
 if (child_pid == 0)
 {
  //This is Child Section
  //Registering the Signal Handler
  signal(SIGINT,catch_signal);
  
  printf("CHILD>>pid=%d Ppid=%d Waiting for Ctrl+C\n",getpid(),getppid());
  fflush(stdout);
  pause();
  
  printf("CHILD>>Caught the signal\n");
 }
 else
 {
  //This is Parent Section
  printf("PARENT>>Waiting couple of seconds to make sure, child waits for SIGINT\n");
  sleep(2);
  kill(child_pid,SIGINT);
  printf("PARENT>>Sent the SIGINT signal to child with pid=%d\n",child_pid); 
  wait(&status);
 }

 return 0;
}

Steps can be defined as:
  1. Process is forked
  2. Child registers signal handler
  3. Child waits for Ctrl+C
  4. Parent sleeps.
  5. Parent sends Ctrl+C using Kill command.
  6. Parent waits for Child to complete
In step 4, if Parent did not sleep, sometimes parents will send Ctrl+C, even before Child executes 'pause'.  Then by the time Child needs Ctrl+C, parent will not be in a position to send Ctrl+C because Parent had already sent it.
When we execute the program

root@kali:/media/root/persistence# ./a.out
PARENT>>Waiting couple of seconds to make sure, child waits for SIGINT
CHILD>>pid=3722 Ppid=3721 Waiting for Ctrl+C

Child waits for Ctrl+C, as Parent is sleeping.  Within moments, the rest of the program executes


root@kali:/media/root/persistence# ./a.out
PARENT>>Waiting couple of seconds to make sure, child waits for SIGINT
CHILD>>pid=3722 Ppid=3721 Waiting for Ctrl+C
SIGNAL FUNCTION>> Caught the signal 2 by process with PID=3722
PARENT>>Sent the SIGINT signal to child with pid=3722
CHILD>>Caught the signal

No comments:

Post a Comment