Jim Raynor
Jim Raynor

Reputation: 49

read() for reading stream from stdin

I am trying to write a C code (running on a Ubuntu Linux OS), which reads from stdin continuously, and receiving varying length of bytes each time. It needs to send back to stdout in 15-bytes-long arrays, whenever the receive buffer reaches or exceeds 15 each time.

Draft Code

#include <stdio.h>
#include <unistd.h>

int main()
{
  char buff[100];

  // Round 1
  read(STDIN_FILENO, buff, 15);
  printf("Part 1:%s", buff);

  // Round 2
  read(STDIN_FILENO, buff, 15);
  printf("Part 2:%s", buff);

  return 0;
}

To give an example with a scenario. We are receiving 30 bytes, in 3 batches and 10 bytes for each time. I used 3 echo commands to represent this in below example scenario.

Also adding expected output, and actual output of current draft code. Any comment or suggestion to have the expected output (maybe another function rather than read and printf ?), would be appreciated.

Scenario

Terminal 1:

mkfifo /tmp/MyPipe
tail -f /tmp/MyPipe | ./StreamProcess

Terminal 2:

echo -ne '1234567890' >> /tmp/MyPipe
echo -ne 'abcdefghij' >> /tmp/MyPipe
echo -ne 'qwertyuiop' >> /tmp/MyPipe

Expected output on Terminal 1

After 1st echo: Nothing is printed

After 2nd echo:

Part 1:1234567890abcde

After 3rd echo:

Part 1:1234567890abcdePart 2:fghijqwertyuiop

Current output (with draft code) on Terminal 1

After 1st echo: Nothing is printed

After 2nd echo:

Part 1:1234567890s·     s·Part 2:abcdefghijs·   s·

After 3rd echo: (only the $ prompt is printed)

Part 1:1234567890s·     s·Part 2:abcdefghijs·   s·$

Upvotes: 1

Views: 4843

Answers (1)

user3629249
user3629249

Reputation: 16550

given the criteria listed in the question, the following code will perform the desired operation.

Edit: incorporated comments to question.

Edit: added error checking

#include <stdio.h>   // printf(), STDIN_FILENO. perror()
#include <unistd.h>  // read(), exit(), EXIT_FAILURE

#define MAX_READ_LEN 15

int main( void)
{
    char buff[ MAX_READ_LEN+1 ];
    int partNum = 0;

    while( 1 )
    {
        // Round 1
        ssize_t bytesRead = read( STDIN_FILENO, buff, MAX_READ_LEN );

        if( 0 > bytesRead )
        {
            perror( "read failed" );
            exit( EXIT_FAILURE );
        }

        // implied else, read successful

        buff[ bytesRead ] = '\0';
        partNum++;
        printf("Part %d:%s\n", partNum, buff);
    }

    return 0;
} // end function: main

Upvotes: 1

Related Questions