2013-01-04 59 views
1

我正在使用Windows Server 2008,并且希望获得DNS服务器。所以我认为最快的方法应该是执行ipconfig,然后使用TProcess解析它的输出。当使用TProcess运行时,控制台应用程序永远不会返回

我已经想出了这个代码:

var 
    proces : TProcess; 
    begin 
    ... 
    proces := TProcess.Create(nil); 
    proces.Executable := 'ipconfig'; 
    proces.Options := proces.Options + [poWaitOnExit,poUsePipes]; 
    try 
    proces.Execute; 
    except 
     proces.Free; 
    end; 
    SetLength(rez,proces.Output.NumBytesAvailable); 
    proces.Output.Read(rez[1],proces.Output.NumBytesAvailable); 
    ShowMessage(rez); 

代码作品,但之后我手动关闭window.I试图poNoConsole控制台但还是同样的结果,过程IPCONFIG保持在任务管理器活跃。

为什么控制台应用程序ipconfig终止?如果我运行它,它会在吐出标准输出信息后退出。

这是我的配置吗?这是一个错误吗?帮帮我!谢谢:)

回答

1

由于ipconfig可以生成很多输出,所以不要试图一次读取它,请使用wiki中的Reading large output方法。

FPC(2.6.2)的下一个迭代将包含大量的runcommand过程,这些过程用于处理一系列常见情况的过程并将输出返回到单个字符串中。

注API的解决方案也是可能的:

{$mode delphi} 

uses JwaIpExport, JwaIpRtrMib, JwaIpTypes,jwawinerror,classes,jwaiphlpapi; 

procedure GetDNSServers(AList: TStringList); 
var 
    pFI: PFixed_Info; 
    pIPAddr: PIPAddrString; 
    OutLen: Cardinal; 
begin 
    AList.Clear; 
    OutLen := SizeOf(TFixedInfo); 
    GetMem(pFI, SizeOf(TFixedInfo)); 
    try 
    if GetNetworkParams(pFI, OutLen) = ERROR_BUFFER_OVERFLOW then 
    begin 
     ReallocMem(pFI, OutLen); 
     if GetNetworkParams(pFI, OutLen) <> NO_ERROR then Exit; 
    end; 
    // If there is no network available there may be no DNS servers defined 
    if pFI^.DnsServerList.IpAddress.s[0] = #0 then Exit; 
    // Add first server 
    AList.Add(pFI^.DnsServerList.IpAddress.s); 
    // Add rest of servers 
    pIPAddr := pFI^.DnsServerList.Next; 
    while Assigned(pIPAddr) do 
    begin 
     AList.Add(pIPAddr^.IpAddress.s); 
     pIPAddr := pIPAddr^.Next; 
    end; 
    finally 
    FreeMem(pFI); 
    end; 
end; 

var v : TStringList; 
    s : string; 
begin 
v:=tstringlist.create; 
getdnsservers(v); 
for s in v do writeln(s); // this probably requires 2.6+ 
v.free; 
end. 
+0

非常感谢,让sense.FPC是美妙的:d – opc0de

+1

注意,API版本使用了不/少64位Windows验证JWA单位。 –

相关问题