You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ada语言中获取进程ID?支持Windows与POSIX平台

在Ada中获取Windows和POSIX平台的进程ID

POSIX平台(Linux、macOS等)

在POSIX兼容系统中,可通过Ada的标准绑定或GNAT工具包获取进程ID:

  • 标准POSIX绑定方式:
    导入POSIX.Process_Identification包,调用Get_Process_ID函数获取进程ID,该函数返回Process_ID类型,可通过POSIX.To_Integer转换为整数。
    示例代码:
    with POSIX; use POSIX;
    with POSIX.Process_Identification; use POSIX.Process_Identification;
    with Ada.Text_IO; use Ada.Text_IO;
    
    procedure Get_PID_POSIX is
        PID : Process_ID := Get_Process_ID;
    begin
        Put_Line("当前进程ID: " & Integer'Image(To_Integer(PID)));
    end Get_PID_POSIX;
    
  • GNAT编译器快捷方式:
    使用GNAT.OS_Lib包中的Get_Pid函数,直接返回整数类型的进程ID:
    with GNAT.OS_Lib; use GNAT.OS_Lib;
    with Ada.Text_IO; use Ada.Text_IO;
    
    procedure Get_PID_GNAT is
        PID : Integer := Get_Pid;
    begin
        Put_Line("当前进程ID: " & Integer'Image(PID));
    end Get_PID_GNAT;
    

Windows平台

Windows下需调用Win32 API的GetCurrentProcessId函数,通过Ada的C接口绑定实现:
导入Interfaces.C包,声明API函数的绑定后调用即可,示例代码:

with Interfaces.C; use Interfaces.C;
with Ada.Text_IO; use Ada.Text_IO;

procedure Get_PID_Windows is
   function GetCurrentProcessId return unsigned_long;
   pragma Import (Stdcall, GetCurrentProcessId, "GetCurrentProcessId");
   PID : unsigned_long := GetCurrentProcessId;
begin
   Put_Line("当前进程ID: " & unsigned_long'Image(PID));
end Get_PID_Windows;

注意:该代码需在Windows环境下使用支持Win32绑定的Ada编译器(如GNAT for Windows)编译。

跨平台兼容实现

通过条件编译可编写跨平台代码,自动适配不同系统:

with Ada.Text_IO; use Ada.Text_IO;

procedure Get_PID_Cross_Platform is
   PID : Integer;
begin
   #if defined (__WIN32__) or defined (__MINGW32__)
      declare
         function GetCurrentProcessId return Integer;
         pragma Import (Stdcall, GetCurrentProcessId, "GetCurrentProcessId");
      begin
         PID := GetCurrentProcessId;
      end;
   #else
      declare
         function Get_Pid return Integer;
         pragma Import (C, Get_Pid, "getpid");
      begin
         PID := Get_Pid;
      end;
   #end if;

   Put_Line("当前进程ID: " & Integer'Image(PID));
end Get_PID_Cross_Platform;

条件编译语法依赖编译器,GNAT支持上述#if格式指令。

内容的提问来源于stack exchange,提问作者Andreas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 02:20:50