Process Signals Programs
Process Signals Programs
C (Linux)
1. Child Kills Parent (fork + kill)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(1);
} else if (pid == 0) {
// Child process
printf("Child process started. PID: %d\n", getpid());
sleep(1); // Let the parent get ready
kill(getppid(), SIGKILL); // Kill parent
printf("Parent process killed by child.\n");
} else {
// Parent process
printf("Parent process PID: %d\n", getpid());
while (1); // Stay alive until killed
}
return 0;
}
void Times_Up() {
printf("\n( TIME FINISH )\n");
exit(0);
}
int main() {
signal(SIGTSTP, Aborted); // Ctrl+Z handling
pid_t pid = fork();
if (pid == 0) {
// Child process
int seconds;
printf("Enter time (in seconds): ");
scanf("%d", &seconds);
for (int i = seconds; i >= 0; i--) {
printf("Time Remaining:%d\n", i);
sleep(1);
}
kill(getppid(), SIGALRM);
exit(0);
} else {
// Parent process
signal(SIGALRM, Times_Up);
wait(NULL); // Wait for child
}
return 0;
}
$ ./Stop_Watch
$ Enter time (in seconds): 5
$ Time Remaining:5
$ Time Remaining:4
$ Time Remaining:3 (Press Ctrl+Z)
$ OPERATION ABBORTED
int main() {
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
int main() {
pid_t p1_pid;
char input;
while (1) {
printf("Enter signal (C=SIGINT, Z=SIGTSTP, K=SIGKILL): ");
scanf(" %c", &input);
if (input == 'C')
kill(p1_pid, SIGINT);
else if (input == 'Z')
kill(p1_pid, SIGTSTP);
else if (input == 'K') {
kill(p1_pid, SIGKILL);
kill(getpid(), SIGKILL);
}
}
return 0;
}
$ ./P2
Enter PID of P1: 12345
Enter signal (C=SIGINT, Z=SIGTSTP, K=SIGKILL): C
-> SIGINT Received
Enter signal (C=SIGINT, Z=SIGTSTP, K=SIGKILL): Z
-> SIGTSTP Received
Enter signal (C=SIGINT, Z=SIGTSTP, K=SIGKILL): K
-> (P1 and P2 both killed)