EmbLogic's Blog

client-server communication using PIPES

server.c:

#include"header1.h"

int main()
{
    pid_t pid_c,pid_p;
    int fd_c[2],fd_p[2],counter=0,pipec_success,pipep_success,stat_val,res;
    char fd_cr[2],fd_cw[2],fd_pr[2],fd_pw[2],*path;
    struct data_format data;

    path = malloc(sizeof(char)*50);

    while(counter < 3)
    {
        pipec_success = pipe(fd_c);
        if(pipec_success != 0)
        {
            perror("Pipe client:");
            return -1;
        }

        sprintf(fd_cr,"%d",fd_c[0]);
        sprintf(fd_cw,"%d",fd_c[1]);

        printf("Enter path\n");
        gets(path);
        pid_c = fork();

        if(pid_c == 0)
        {
            execl(path,fd_cw,"input",NULL);
        }

        if(pid_c != 0)
            wait(&stat_val);

        read(fd_c[0],&data,sizeof(data));
        //printf("read data is %d %d %c",data.num1,data.num2,data.operation);
        pipep_success = pipe(fd_p);
        if(pipep_success != 0)
        {
            perror("Pipe process:");
            return -1;
        }

        write(fd_p[1],&data,sizeof(data));

        sprintf(fd_pr,"%d",fd_p[0]);
        sprintf(fd_pw,"%d",fd_p[1]);

        switch (data.operation)
        {
            case '+':
                pid_p = fork();

                if(pid_p == 0)
                {
                    execl("/home/ritu/emblogic/project_3/adder",fd_pr,fd_pw,NULL);
                }

                if(pid_p != 0)
                wait(&stat_val);
                break;
            case '-':
                pid_p = fork();

                if(pid_p == 0)
                {
                    execl("/home/ritu/emblogic/project_3/subtractor",fd_pr,fd_pw,NULL);
                }

                if(pid_p != 0)
                    wait(&stat_val);
                break;
            case '*':
                 pid_p = fork();

                if(pid_p == 0)
                {
                    execl("/home/ritu/emblogic/project_3/multiplier",fd_pr,fd_pw,NULL);
                }

                if(pid_p != 0)
                    wait(&stat_val);
                break;
        }

        read(fd_p[0],&res,sizeof(res));
        write(fd_c[1],&res,sizeof(res));
        pid_c = fork();
        if(pid_c == 0)
        {
            execl(path,fd_cr,fd_cw,"output",NULL);
        }

        if(pid_c != 0)
            wait(&stat_val);

        counter++;
    }
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>