Search code examples
multithreadingdelphicgiisapi

Can I create a unique filename based on ProcessID and ThreadID?


I have a delphi (Win32) web application that can run either as a CGI app, ISAPI or Apache DLL. I want to be able to generate a unique filename prefix (unique for all current requests at a given moment), and figure that the best way to do this would be to use processID (to handle CGI mode) as well as threadID (to handle dll mode).

How would I get a unique Process ID and Thread ID in Delphi?

Will these be unique in a Multi-Core/Multi-Processor situation (on a single webserver machine)?

Edit: please note that I was advised against this approach, and thus the accepted answer uses a different method to generate temporary filenames


Solution

  • you have many good ideas presented here.

    Does it also create an empty file to "get a lock on" the name?

    no; i believe we rely on Windows to ensure the same temp file name is never given twice on the same computer since boot time.

    is there any chance of a clash if there is a split second delay between generating the name and creating the file (if I need to create the file myself).

    no; that'd be a pretty bad thing.

    here's a routine i've been using for getting a temp file.

    function GetTemporaryFileName:string;
    var
      Path, FileName: array[0..MAX_PATH] of Char;
    begin
      Win32Check(GetTempPath(MAX_PATH, Path) <> 0);
      Win32Check(GetTempFileName(Path, '~EX', 0, FileName) <> 0);
      Result:=String(Filename);
    end;
    

    you could instead use FileGetTempName( ) from JclFileUtils.pas in JCL.