user2277536
user2277536

Reputation: 55

how to stop reading "cat /dev/urandom"?

i am writing a program that read the standard input.i have a loop like this :

while(read(0, buffer, sizeof(buffer)) > 0)

it works fine, but when i do a cat /dev/urandom | ./myprogram the loop never stop.So i would like to stop reading after some time elapsed.

Upvotes: 2

Views: 2354

Answers (3)

autistic
autistic

Reputation: 15642

I had a problem like this not long ago. You could use time and difftime, for example like this:

time_t t = time(NULL);
double max_seconds = 1.0;
while (read(0, buffer, sizeof(buffer)) > 0 && difftime(time(NULL), t) < max_seconds) {
    /* ... */
}

Upvotes: 0

alk
alk

Reputation: 70981

You might like to set an alarm using alarm().

alarm(1);

{
  size_t ssizeReadTotal = 0;

  {
    ssize_t ssizeRead = 0;

    while (0 < (ssizeRead = read(0, buffer + sizeReadTotal, sizeof(buffer) - sizeReadTotal)))
    {
      sizeReadTotal += ssizeRead;
    }

    if (0 > ssizeRead) 
    {
      if (EINTR == errno))
      {
        fprintf(stderr, "Filling the buffer was interrupted by alarm clock.\n");

      }
      else /* some *real* error occurred */
      {
        perror("read()");
      }
    }
  }

  if (sizeof(buffer) > sizeReadTotal)
  {
    fprintf(stderr, "The buffer was not fully initialised!\n");
  }
}

This signals SIGALRM after one second. The signal interupts the call to read(). It will return -1 and set errno to EINTR.

Also the read()ing stops when the buffer had been filled.

Upvotes: 1

mjuarez
mjuarez

Reputation: 16844

Do this instead, to get 2K of random data into myprogram:

  cat /dev/urandom | head -c 2000 | ./myprogram

Upvotes: 2

Related Questions