Ishan Joshi
Ishan Joshi

Reputation: 35

Not able to pass strings through named pipes (FIFOs) in multithreaded processes

I am trying to use 'FIFOs' and 'popen()' function for communication between multiple processes. Also, the first process is multithreaded for reading and writing operations.

Following is the C code for the processes:

P1 process (Q1.c)

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>

void* reader()
{   
    char string[64];
    int rfd = open("FIFO",O_RDONLY);
    while(1)
    {
        read(rfd,string,sizeof(string));
        sleep(10);
        printf("%s\n",string);
    }   
}
void* writer()
{
    char string[64];
    FILE *wfd = popen("./Q1_1","w");
    int fd = fileno(wfd);
    while(1)
    {
        scanf("%s",string);
        write(fd,string,sizeof(string));
    }
    pclose(wfd);
}
int main()
{
    if(mkfifo("FIFO",0666)==-1)
    {
        if(errno!=EEXIST)
        {
            return 1;
        }
    }
    pthread_t r_thread,s_thread;
    pthread_create(&r_thread,NULL,reader,NULL);
    pthread_create(&s_thread,NULL,writer,NULL);
    pthread_join(r_thread,NULL);
    pthread_join(s_thread,NULL);
    return 0;
}

P2 Process (Q1_1.c)

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>

int main()
{
    FILE *fd = popen("./Q1_2","w");
    char string[64];
    int ffd = fileno(fd);
    printf("P2Check");
    while(1)
    {
        scanf("%s",string);
        write(ffd,string,sizeof(string));
    }
    return 0;
}

P3 Process (Q1_2.c)

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>

int main()
{
    char string[64];
    if(mkfifo("FIFO",0666)==-1)
    {
        if(errno!=EEXIST)
        {
            return 1;
        }
    }
    int wfd = open("FIFO",O_WRONLY);
    printf("P3Check");
    while(1)
    {
        scanf("%s",string);
        write(wfd,string,sizeof(string));
    }
}

However, after executing process P1 and providing input, there is no output as if the process is stuck. I suspect there is some issue with the multithreading but not sure.

Upvotes: 0

Views: 123

Answers (0)

Related Questions