Here's an example C program that meets the requirements:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
// Global variables to keep track of process ids
pid_t main_pid, child1_pid, child2_pid, child3_pid;
// Signal handler for CTR-C
void signal_handler(int sig)
{
if (getpid() == main_pid) {
// Terminate all non-descendant processes
if (getpgid(child1_pid) != getpgid(child2_pid)) {
kill(-getpgid(child1_pid), SIGTERM);
printf("Process %d (parent: %d) terminated\n", child1_pid, getpid());
if (getpgid(child2_pid) != getpgid(child3_pid)) {
kill(-getpgid(child2_pid), SIGTERM);
printf("Process %d (parent: %d) terminated\n", child2_pid, getpid());
if (getpgid(child3_pid) != getpgid(getpid())) {
kill(-getpgid(child3_pid), SIGTERM);
printf("Process %d (parent: %d) terminated\n", child3_pid, getpid());
}
}
}
}
exit(0);
}
int main()
{
main_pid = getpid();
// Create the first child process
child1_pid = fork();
if (child1_pid == -1) {
perror("fork");
exit(1);
}
if (child1_pid == 0) {
// Child process 1 infinite loop
while (1) {
printf("From process %d\n", getpid());
sleep(2);
}
}
// Create the second child process
child2_pid = fork();
if (child2_pid == -1) {
perror("fork");
exit(1);
}
if (child2_pid == 0) {
// Child process 2 infinite loop
while (1) {
printf("From process %d\n", getpid());
sleep(2);
}
}
// Create the third child process
child3_pid = fork();
if (child3_pid == -1) {
perror("fork");
exit(1);
}
if (child3_pid == 0) {
// Child process 3 infinite loop
while (1) {
printf("From process %d\n", getpid());
sleep(2);
}
}
// Set the process group id for child processes
if (setpgid(child1_pid, main_pid) == -1 ||
setpgid(child2_pid, main_pid) == -1 ||
setpgid(child3_pid, main_pid) == -1) {
perror("setpgid");
exit(1);
}
// Set signal handler for CTR-C
signal(SIGINT, signal_handler);
// Main program infinite loop
while (1) {
printf("This is from process %d\n", getpid());
sleep(2);
kill(child1_pid, SIGSTOP);
kill(child2_pid, SIGCONT);
sleep(2);
kill(child2_pid, SIGSTOP);
kill(child3_pid, SIGCONT);
sleep(2);
kill(child3_pid, SIGSTOP);
kill(child1_pid, SIGCONT);
}
return 0;
}
When you run the program, each forked process will run an infinite loop printing "From process (process id)" every two seconds. Pressing CTR-C will terminate all non-descendant processes, and they will print their PID and PPID along with a termination message. After that, the main program and its direct descendants will take turns every two seconds to print the statement "This is from process (process id)" without interleaving or disorder.