0

Let's say i create via fork a child process from a father process and i pass an X value to child process using a pipe.At first the child is on pause and i start it using a SIGINT signal.What i want to do is pass the value X to the signal handler used in pipe.Also,the value of i will change during the running of father process and i will have to pass it multiple times so i don't think making it global would work.Code:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>


void handler() {
    //i would like to print the value of i here.
}

int main() {
    int fd[2], s;
    pipe(fd);
    pid_t c = fork();

    if (c == 0) {
        signal(SIGINT, handler);
        pause();
        read(fd[0], &s, sizeof(s));
        //if use printf("%d",s) here s=2 correctly.
    }
    if (c > 0) {
        int i = 2;
        sleep(1);               //i don't want the SIGINT signal to terminate the child process so i wait for it to reach pause
        kill(c, SIGINT);
        write(fd[1], &i, sizeof(i));
    }
}

How could this be done?

Simon Doppler
  • 1,918
  • 8
  • 26

1 Answers1

0

Add a global variable with value 0 at the start of the child. Put a while loop in the child. When the signal comes turn it to 1. In the while loop test for the value of the global variable if it turns to one, if so read and print and turn back the variable to 0.

Example

#include <stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/wait.h>


int signal_received = 0;

void handler(){
    signal_received = 1;
}

int main(){
int fd[2],s;
pipe(fd);
pid_t c=fork();

if(c==0){
    signal(SIGINT,handler);
    while (1)
    {
        if (signal_received)
        {
            read(fd[0],&s,sizeof(s));
            printf("%d",s);
            signal_received = 0;
        }
    }
    pause();
    read(fd[0],&s,sizeof(s));
 //if use printf("%d",s) here s=2 correctly.
 }
if(c>0){
int i=2;
sleep(1);//i don't want the SIGINT signal to terminate the child process so i wait for it to reach pause
kill(c,SIGINT);
write(fd[1],&i,sizeof(i));
}
}

Of course, this is a stub to what you want, there is more.

You can add concurrent protection on the global variable.

If you have a more complex system, then a messaging queue would be more appropriate.

Hope it helps :)

Community
  • 1
  • 1
Meher Khiari
  • 111
  • 9
  • Thank you for your answer,it solves my problem.Although i would like to print s inside the handler if possible .Is there a way to pass it from the child to the function? –  Mar 22 '19 at 16:47
  • 1
    `signal_received` needs to be `volatile`. See https://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c?rq=1 – Andrew Henle Mar 22 '19 at 17:29