Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - How to prevent application hang when writing to LPT port

Tags:

delphi

I have an application what writes commands to some specialized printers directly on LPT1 port. The code looks like this:

AssignFile(t, 'LPT1');
Rewrite(t);

Write(t,#27 + '@');          // initialize
Sleep(50);                   // avoid buffer fill
Write(t,#27#32 + Chr(0));    // set default font
...

The problem is that when the printer is not connected to the port, the first Write instruction doesn't do anything, it just hangs up and the entire thread is locked.

Is there a way to define a timeout for these instructions, or can you recommend another library that could do this job? It would be great if it had a Write function similar to the one in Delphi, because the amount of code using this approach is very large, and it would be very hard to change all of it.

like image 345
Valentin Istrate Avatar asked Mar 16 '23 15:03

Valentin Istrate


1 Answers

Move your printing code to a separate thread. The built-in text-file functions don't have any timeout mechanism, but you can tell the OS to cancel any pending I/O operations whenever you decide that too much time has passed.

I'd start with CancelSynchronousIo, which cancels all I/O on a given thread. It should allow you to keep all your existing Write calls. Be prepared to handle when they fail upon being cancelled.

That function requires Windows Vista or higher, which shouldn't be a problem nowadays, but won't work if you still need support for Windows XP. In that case, you'll need to use CreateFile to open the port for overlapped I/O. Then you can use CancelIo or CancelIoEx. You'll need to replace all your Write calls since the built-in Delphi functions don't support overlapped operations.

like image 170
Rob Kennedy Avatar answered Apr 30 '23 07:04

Rob Kennedy