please help a problem in client-server ipc message 2 pipes communication simple example

I want to have a message send & receive through 2 half-duplex pipes

Flow of data

top half pipe

stdin--->parent(client) fd1[1]--->pipe1-->child(server) fd1[0]

bottom half pipe

child(server) fd2[1]---->pipe2--->parent(client) fd2[0]--->stdout

I need to have boundary structed message mesg_len+mesg_type+mesg_data

#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <fcntl.h> 
#include <errno.h> 
#include <string.h> 
#include <sys/wait.h> 
 
#define MAX_BUF 100 
#define MAXMESGDATA (MAX_BUF - 2* sizeof(long)) 
#define MESGHDRSIZE (sizeof(struct mymesg)-MAXMESGDATA) 
 
struct mymesg{ 
    long mesg_len; //byte in mesg_data 
    long mesg_type; //message type 
    char mesg_data[MAXMESGDATA]; 
}; 
 
ssize_t mesg_send(int,struct mymesg *); 
ssize_t mesg_recv(int,struct mymesg *); 
void client (int,int),server(int,int); 
 
int main(int argc, char ** argv){ 
    //MAXMESGDATA== 92 bytes 
    //sizeof(struct mymesg)== 100 bytes 
    //2* sizeof(long)== 8 bytes 
    //MESGHDRSIZE ==8 bytes 
 
    int pipe1[2],pipe2[2]; 
    pid_t childpid; 
    pipe(pipe1); //create 2 pipes 
    pipe(pipe2); 
 
    if ((childpid=fork())==0) { //child 
        close(pipe1[1]); 
        close(pipe2[0]); 
        server(pipe1[0],pipe2[1]); 
        exit(0); 
    } 
    //parent 
    close(pipe1[0]); 
    close(pipe2[1]); 
    client(pipe1[1],pipe2[0]); 
    waitpid (childpid,NULL,0); 
    return EXIT_SUCCESS; 
} 
 

You've got the parameters for client() wrong. You're giving it a readfd which is the write-end of the wrong pipe, and a writefd which is the read-end of the other wrong pipe. Try client(pipe2[0], pipe1[1]);

Also keep in mind that the message from the child only gets flushed because it quits. Pipes have a long buffer. If you try to wait for a message from the client when it hasn't quit, you could just block forever. (Leaving in the newlines might help.)

1 Like