Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I keep a Free Pascal console application running "forever"?

In a Linux Free Pascal 2.6.0 console application, a HTTP server is started and runs in a separate thread, so the call to Start will immediately return.

begin
  ...
  MyHTTPServer.Start;
  ...
  WriteLn('Application terminated');
end;

To keep the console from closing I could use a simple endless loop like:

// wait, read and ignore input from stdin
while True do ReadLn;

or

// Sleep as long as possible
while True do Sleep(MaxInt);

Which one would you prefer? Or is there a better way to keep the application running?

like image 910
mjn Avatar asked Dec 30 '12 12:12

mjn


2 Answers

That is a very good question, and I don't know why people voted it down. One up from me.

It is not just a matter of waiting forever ( while checkforsomeevent do sleep(10); will do that where checkforsomeevent checks for whatever event you want to terminate on, or TRUE if you don't. Since the thread has nothing to do, sleep(0) seems a waster of resources)

The bigger problem is that Windows will terminate long running console programs that initialize threading support after a while because it thinks they "hang".

I'm not entirely sure this is on (wall) running time, or CPU resources though.

The Free Pascal help compiler chmcmd can run a long time (minutes, because it is compressing html). It supports threading on *nix, but I never got it to work properly under Windows. (and admittedly, since chmcmd is mostly used on *nix, it was not a high priority item)

I back then researched a bit, and it seems you must register a windowhandle and process messages to avoid this. I tried this but failed, and can't find the patch atm, it is probably on my work system.

like image 121
Marco van de Voort Avatar answered Nov 15 '22 09:11

Marco van de Voort


On Linux you can call pause() which blocks until a signal is received. You'd therefore need to call pause() is a loop. The advantage of this over sleeping is that you process can be terminated by a termination signal.

like image 22
David Heffernan Avatar answered Nov 15 '22 07:11

David Heffernan