Click here to Skip to main content
15,887,854 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
a)
How can I add message passing from parent to child using a pipe and if an interrupt from the keyboard (Ctrl+C) is issued, 

b)then the program must have interrupt message?


What I have tried:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    int pid, pid1, pid2;
  
   
    pid = fork();
  
    
    if (pid == 0) {
  
        
        sleep(3);
  
       
        printf("child[1] --> pid = %d and ppid = %d\n",
               getpid(), getppid());
    }
  
    else {
        pid1 = fork();
        if (pid1 == 0) {
            sleep(2);
            printf("child[2] --> pid = %d and ppid = %d\n",
                   getpid(), getppid());
        }
        else {
            pid2 = fork();
            if (pid2 == 0) {
               
                printf("child[3] --> pid = %d and ppid = %d\n",
                       getpid(), getppid());
            }
  
           
            else {
                
                sleep(3);
                printf("parent --> pid = %d\n", getpid());
            }
        }
    }
    
    
    

    return 0;
}
Posted
Updated 27-Jul-22 8:14am

 
Share this answer
 
15 Pipes and FIFOs
hwww.gnu.org/software/libc/manual/html_node/Pipes-and-FIFOs.html
24 Signal Handling
www.gnu.org/software/libc/manual/html_node/Signal-Handling.html

For Ctl-C you have to register a signal handler for the signal SIGINT.
// Register signals 
signal(SIGINT, my_handler);

If the signal is triggered, the signal handler is processed, which then
sets a variable, or performs other tasks.
void my_handler(int sig){ // can be called asynchronously
  flag = 1; // set flag
}

Alternatively, you can also wait for the signal with sigwait().
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900