program TestIPCConTimeout;

{$APPTYPE CONSOLE}

uses
{$IFDEF WINDOWS}
  ipcthrd in '..\..\src_libnettopos\fctopos\IPC\Win32\ipcthrd.pas',
  windows,
{$ELSE}
  timeLib in '..\..\src_libnettopos\fctopos\timeLib.pas',
  uemuladorwinipc in '..\..\src_libnettopos\fctopos\IPC\Linux\uemuladorwinipc.pas',
  usemaforopolenta in '..\..\src_libnettopos\fctopos\IPC\Linux\usemaforopolenta.pas',
  ipcobjs in '..\..\src_libnettopos\fctopos\IPC\Linux\ipcobjs.pas',
  uKeyDir in '..\..\src_libnettopos\libnettopos\uKeyDir.pas',
  baseunix,
{$ENDIF}
  SysUtils;

var
  nomSmf: String;

procedure crearArchiKey;
{$IFNDEF WINDOWS}
var
  f: TextFile;
  path: String;
{$ENDIF}
begin
{$IFNDEF WINDOWS}
  nomSmf:= fpgetenv('HOME') + '/archikeys/keyTestIPCConTimeOut';
  if not FileExists(nomSmf) then
  begin
    path:= ExtractFilePath(nomSmf);
    if not DirectoryExists(path) then
      ForceDirectories(path);
    AssignFile( f, nomSmf );
    Rewrite( f );
    writeln( f, 'ArchiKey: ', nomSmf, ' - no borrar.' );
    closefile( f );
  end;
{$ELSE}
  nomSmf:= 'keyTestIPCConTimeOut';
{$ENDIF}
end;

var
  Mutex: TMutex;
  invFrec: Double;
  ticsIni, ticsFin, frec64: Int64;
  timeOut: Integer;
begin
  if ParamCount >= 1 then
  begin
{$IFDEF WINDOWS}
    Windows.QueryPerformanceFrequency(frec64);
{$ELSE}
    timeLib.QueryPerformanceFrequency(frec64);
{$ENDIF}
    invFrec:= 1000 / frec64;

    timeOut:= StrToInt(ParamStr(1));
    crearArchiKey;
{$IFDEF WINDOWS}
    Mutex:= TMutex.Create(nomSmf);
    Windows.QueryPerformanceCounter(ticsIni);
{$ELSE}
    Mutex:= TMutex.Create(nomSmf, 1);
    timeLib.QueryPerformanceCounter(ticsIni);
    writeln('PID= ', fpGetPid);
{$ENDIF}
    Writeln('Cree semaforo mutex "', nomSmf, '"');
    Writeln;
    if Mutex.Get(timeOut) then
    begin
{$IFDEF WINDOWS}
      Windows.QueryPerformanceCounter(ticsFin);
{$ELSE}
      timeLib.QueryPerformanceCounter(ticsFin);
{$ENDIF}
      writeln('Obtuve mutex con timeOut = ' + ParamStr(1) + ' en ' + FloatToStrF((ticsFin - ticsIni) * invFrec, ffFixed, 8, 2) + 'ms');
      writeln('Presione <Enter> para liberar');
      readln;
      mutex.Release;
    end
    else
    begin
{$IFDEF WINDOWS}
      Windows.QueryPerformanceCounter(ticsFin);
{$ELSE}
      timeLib.QueryPerformanceCounter(ticsFin);
{$ENDIF}
      writeln('No obtuve mutex con timeOut = ' + ParamStr(1) + ' en ' + FloatToStrF((ticsFin - ticsIni) * invFrec, ffFixed, 8, 2) + 'ms');
    end;
    mutex.Free;
    writeln('Chau');
  end
  else
    writeln('Uso: TestIPCConTimeout.exe timeOut[ms]');
end.
