curiousMind_85
curiousMind_85

Reputation: 167

Unable to send or receive data via a FIFO in C

I'm workng on a C program with which I'd like to implement a scenario when a parent and two children processes are communicating with each other. A child should send a real-time signal to the parent. That's not a problem. However, in case the parent would like to write the FIFO in order for the child to access its message, then I'm unable to achieve the deisred goal.

As you can see so far I'm only experimenting with a single child. If this setup will work then I'd like to expand the problem to children.

I attempted to accomplish the desired outcome with the help of the SIGRTMIN+1 constant. With it I ensure the presence of a real-time signal. In the parent following the sigsuspend call I attempt to open the FIFO for writing only. In the child following the sigqueue call I attempt to open the FIFO for reading only.

EDIT: I know that printf() inside a handler function body is not desired, but I'm only including that for experimenting purposes.

#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

#define SIG_CHLD_1_READY SIGRTMIN+1

int main()
{
pid_t parent = getpid();
sigset_t newmask, oldmask;
char* fifo = "/tmp/nohope";
mkfifo( fifo, S_IRUSR|S_IWUSR );

    if ( fork() == 0) {    /*Child*/
        union sigval sval; 
        sval.sival_int = 1;
    
        sigqueue( parent, SIG_CHLD_1_READY, sval); 

        int fd = open( fifo, S_IRUSR);
        int a;
        while( read(fd, &a, sizeof( int ) ) == sizeof( int ) );

        printf("%d\n", a );
        
        _exit(0);
        
    }
    else {                             /* Parent */
        struct sigaction action;
        void catchit();

        sigemptyset(&newmask);
        sigaddset(&newmask, SIG_CHLD_1_READY);
        sigprocmask(SIG_BLOCK, &newmask, &oldmask);

        action.sa_flags = SA_SIGINFO; 
        action.sa_sigaction = catchit;

        if (sigaction(SIG_CHLD_1_READY, &action, NULL) == -1) { 
            perror("sigusr: sigaction");
            _exit(1);
        }
        sleep(1); 

        sigsuspend(&oldmask);

        int fd = open( fifo, S_IWUSR);
        int a = 69;
        write(fd, &a, sizeof( int ));

        
        wait( NULL );
    }
}
void catchit(int signo, siginfo_t *info, void *extra) 
{
       void *ptr_val = info->si_value.sival_ptr;
       int int_val = info->si_value.sival_int;
       printf("Signal %d, value %d  received from parent\n", signo, int_val);
       _exit(0);
}

Thank you very much in advance!

EDIT: Solution was to remove _exit(0);

Upvotes: 0

Views: 64

Answers (0)

Related Questions