Sunday, April 15, 2018

Catching Signal, with fork

Today, I will demonstrate signals, by forking a child. 

 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("Inside the signal function %d PID=%d\n", sig_num,getpid());
 fflush(stdout);
}

int main()
{
 pid_t child_pid;
 int status;

 // Registering the Signal Handler
 signal(SIGINT,catch_signal);

 child_pid=fork();
 
 if (child_pid == 0)
 {
  //This is Child Section
  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>>pid=%d Ppid=%d Waiting for Ctrl+C\n",getpid(),getppid());
  fflush(stdout);
  pause();
  printf("PARENT>>Caught the signal\n");
  
  wait(&status);
 }

 return 0;
}

Summary of what I did:
  1.  Created a signal handling function
  2. Registered signal
  3. Forked the process
  4. Child, waits for the signal Ctrl+C
  5. parent also waits for the signal Ctrl+C
 After I executed

root@kali:/media/root/persistence# ./a.out
PARENT>>pid=2869 Ppid=2344 Waiting for Ctrl+C
CHILD>>pid=2870 Ppid=2869 Waiting for Ctrl+C

Execution 1:

When I hit Ctrl+C in the terminal, Parent and Child got terminated at the same time.

root@kali:/media/root/persistence# ./a.out
PARENT>>pid=2869 Ppid=2344 Waiting for Ctrl+C
CHILD>>pid=2870 Ppid=2869 Waiting for Ctrl+C
Inside the signal function 2 PID=2870
CHILD>>Caught the signal
Inside the signal function 2 PID=2869
PARENT>>Caught the signal

Execution 2:

From another terminal if I pass SIGINT individually to parent and child. They catch signal


root@kali:/media/root/persistence# ./a.out
PARENT>>pid=3119 Ppid=2344 Waiting for Ctrl+C
CHILD>>pid=3120 Ppid=3119 Waiting for Ctrl+C

From another terminal, I issue 'kill -s 2 3119' to the parent process. Parent executes the signal handling function.


root@kali:/media/root/persistence# ./a.out
PARENT>>pid=3119 Ppid=2344 Waiting for Ctrl+C
CHILD>>pid=3120 Ppid=3119 Waiting for Ctrl+C
Inside the signal function 2 PID=3119
PARENT>>Caught the signal
 
Then I issue 'kill -s 2 3120'


root@kali:/media/root/persistence# ./a.out
PARENT>>pid=3119 Ppid=2344 Waiting for Ctrl+C
CHILD>>pid=3120 Ppid=3119 Waiting for Ctrl+C
Inside the signal function 2 PID=3119
PARENT>>Caught the signal
Inside the signal function 2 PID=3120
CHILD>>Caught the signal

No comments:

Post a Comment