1

In Linux command stty we can set the N characters minimum for a completed read using the option min.

From stty man

min N
    with -icanon, set N characters minimum for a completed read 
time N
    with -icanon, set read timeout of N tenths of a second

Is there a way to set these options [ min and time] using fcntl() or any C API's. I checked the fcntl() and open() man , but couldn't find a matching flag.

Clifford
  • 88,407
  • 13
  • 85
  • 165
AKV
  • 425
  • 7
  • 20

2 Answers2

2

In Linux command stty we can set the N characters minimum for a completed read using the option min.

Is there a way to set these options [ min and time] using fcntl() or any C API's.

The stty command is merely a command that accesses the termios interface (of a serial terminal).
Programmatically you can use tcgetattr() and tcsetattr().

See Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems


Sample C code that sets the deciseconds and minimum-count for a raw read of an open serial terminal:

int set_time_and_min(int fd, int time, int min)
{
  struct termios settings;
  int result;

  result = tcgetattr(fd, &settings);
  if (result < 0) {
      perror("error in tcgetattr");
      return -1;
  }
  settings.c_cc[VTIME] = time;
  settings.c_cc[VMIN] = min;
  result = tcsetattr(fd, TCSANOW, &settings);
  if (result < 0) {
      perror("error in tcsetattr");
      return -2;
  }
  return 0;
}

I checked the fcntl() and open() man , but couldn't find a matching flag.

The man page to reference is termios(3).


Of course the VMIN and VTIME values are only effective when using blocking noncanonical I/O. See Linux Blocking vs. non Blocking Serial Read

sawdust
  • 16,103
  • 3
  • 40
  • 50
  • I realized that I can not use fcntl() to set VMIn and VTIME. So the alternative option is termios and it works. Thanks. – AKV Jun 06 '19 at 14:15
0

Assuming you mean the POSIX ssize_t read(int fildes, void *buf, size_t nbyte), no. There is no standard way to set a minimum number of bytes to be read(). (I can't rule out some implementations providing the capability, but I'm not aware of any, nor for the reasons to follow do I see a point in providing such a capability to read() in general.)

And for a very good reason: what happens if the bytes run out before the number requested is met? The other end of the pipe gets closed, the socket you're reading from gets shut down, or you hit the end of the file you're reading from before reaching the requested number of bytes.

What should read() do then? Block forever waiting for bytes that either might never or can never arrive? In that case, the only sensible action is for read() to return the number of bytes that have been read.

So in general you must handle partial read() results anyway, making the "read a minimum number of bytes" setting pointless.

Community
  • 1
  • 1
Andrew Henle
  • 32,625
  • 3
  • 24
  • 56