I am wondering that since the serial port can't be used by two programs at the same time, how my barcode reader(hardware device) is able to send data to my computer via serial port, while the port is being opened by my program, and monitored for the newly coming data.
1 Answers
Sure, only one process can open the port. On the other end of it sits the device driver, it actually talks to the hardware.
That hardware is a chip called an UART, Universal Asynchronous Receiver Transmitter. It connects to the wire you use to hook up the device. Any data that comes in through the RxD pin on the connector gets converted to bytes by the UART. The device driver responds to the chip's interrupt and copies the byte(s) from the UART's receive buffer into the driver's receive buffer. Ready to be consumed by a program, it calls ReadFile() to empty the buffer. Today it is often a USB device driver that emulates a serial port.
Serial port communications are very primitive, there is no notion of a logical connection and no agreed-upon protocol to label received data to belong to a specific connection or consumer. Nothing similar to UDP or TCP, the protocols that allows a network connection to be shared. Serial ports site at the very bottom of the OSI model, the physical layer. The driver therefore does not allow more than one program to open the port. It is first-come, first serve.