Search code examples
processoperating-systemada

How to get process id in Ada?


I want to make a method returning the calling process id, but can't seem to find how to do that in Ada. Must be looking in the wrong places.

How to get process id on windows and POSIX platforms?


Solution

  • The Florist binding to POSIX should work, but it is quite a sizeable library. Here is a simpler binding example, tested on Mac OS-X:

    with Ada.Text_IO;
    with Interfaces.C;
    procedure My_Pid
    is
       function Get_Pid return Interfaces.C.int
       with Import, Convention => C, External_Name => "getpid";
    begin
       Ada.Text_IO.Put_Line (
          "My PID is" & Interfaces.C.int'Image (Get_Pid));
    end My_Pid;
    

    This assumes that the POSIX type pid_t, defined in <unistd.h>, is compatible with Interfaces.C.int, which may not hold on all POSIX platforms; the alternative AIUI is Interfaces.C.long.

    I don't have access to a Windows system to test, but it seems there is a _getpid function (https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getpid?view=msvc-170), with getpid (no leading underscore) as a deprecated alias (https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/posix-getpid?view=msvc-170).

    There is also an extensive binding to the Win32 API, similar in scope to Florist, at https://github.com/AdaCore/win32ada.