Tookmund
Tookmund

Reputation: 103

Connect socket and FIFO pipe

I am trying to connect a socket to a FIFO pipe, but can't find an easy way to do it.

At the moment I am using:

 char localbuf[2];

    while(1) {
            memset(localbuf,0,sizeof(localbuf));

            ret = read(sfd,localbuf,1);
            test(ret,"Unable to read from socket");

            ret = write(out,localbuf,1);
            test(ret,"Unable to write to out FIFO");

            read(in,localbuf,1);
            test(ret,"Unable to read from in FIFO");

            write(sfd,localbuf,1);
            test(ret,"Unable to write to socket");
    }

However, this seems horribly inefficient and wrong because it should not send the data until it receives a newline but cannot know beforehand how much data there will be.

Complete code here

Is there a better way?

Upvotes: 0

Views: 918

Answers (1)

Giuseppe Guerrini
Giuseppe Guerrini

Reputation: 4426

Some hints to have a bigger throughput:

1) Set the non-blocking mode on file descriptors. Example here

2) Use "select" or "poll" to wait until data are coming in (many examples availabe, an explanation is here)

3) Enlarge the read buffers (e.g. up to 4 kb), so you can receive more data in a single call. Use the read's return value to know how many bytes you have actually received.

4) write the whole received buffer. Check write's return value to know how many bytes have been actually transferred, write may send less then you requested. In that case (probably congestion) send the remaining data later. "select" is able to signal you also if a fd is ready to be written. The whole logic becomes quite complicated, but if the throughput is your goal you probably have to deal with it.

5) Also, you can split your loop in two sepatare threads, one for the in->sfd direction and one for sfd->out direction. Many of the previous notes still apply.

Upvotes: 1

Related Questions