Reading from a TTY

Hi all,
I am trying to read from a TTY, say ttyp2.

Writing to it is no problem; I do an fp=fopen(“dev/ttyp2”, “w”) and then fprintf(fp, “foo”) ).

Using cat /dev/ttyp2 also works and shows me the “foo” that has been written to TTY2.

But I am not able to read from the TTY with a C-Function. I tried to use fopen("/dev/ttyp2", “r”) and then fread, fgets, fgetc and so on.

Does anybody know how to do it?


I’ve just found out that the “cat /dev/ttyp2” blocks the read operation that the C-program tried to do.

Other way round, when I start the C-program first, I can’t use “cat” anymore.

Why is there exclusive access only?

I have read about the O_NONBLOCK Flag, but I can’t provide it to the fopen function.

And when using open() and read() instead of fopen and fread, there is heavy CPU-load.
fread() seems to “sleep” until there is new data on tty2, and that’s exactly what I want (I don’t want to waste CPU time by waiting for data on tty).

It sounds like you are opening the same input device twice. I believe the authoritative Unix/Posix result is that “results will be unpredictable”. That is, when you have two requests for input, who gets the data is up for grabs. This is not the same as exclusive access.

O_NONBLOCK can be applied to fopen if you know how, but I don’t think you want to. Turning it on causes read()'s to NOT BLOCK, so unless you put in a sleep in your code you will suck up all CPU in a read() loop.

A good question now is why are you reading from a device that is also being read by cat? What are you trying to accomplish? How would you like to the device to act in this case. If it is something reasonable and rational that the standard device does not do, you could create a resource manager that would inject a software layer that can control things the way you want.