系统命令执行但立即进入后台

System command executes but is immediately backgrounded

我正在尝试使用 TProcess 单元执行 ssh 以连接到我的一台服务器并向我提供 shell。这是对我在 Ruby 中的一个重写,因为 Ruby 的执行时间非常慢。当我 运行 我的 Process.Execute 函数时,我看到了 shell 但它立即进入后台。 运行 pgrep ssh 显示它是 运行ning 但我无法访问它,使用 fg 不会将其恢复。该段代码如下:

  if HasOption('c', 'connect') then begin
    TempFile:= GetRecord(GetOptionValue('c', 'connect'));
    AProcess:= TProcess.Create(nil);
    AProcess.Executable:= '/usr/bin/ssh';
    AProcess.Parameters.Add('-p');
    AProcess.Parameters.Add(TempFile.Port);
    AProcess.Parameters.Add('-ntt');
    AProcess.Parameters.Add(TempFile.Username + '@' + TempFile.Address);
    AProcess.Options:= [];
    AProcess.ShowWindow:= swoShow;
    AProcess.InheritHandles:= False;
    AProcess.Execute;
    AProcess.Free;
    Terminate;
    Exit;
  end;

TempFileTProfile类型的变量,是包含服务器信息的记录。编目系统和检索工作正常,但拉起 shell 没有。

...
AProcess.ShowWindow:= swoShow;
AProcess.InheritHandles:= False;
AProcess.Execute;
AProcess.Free;
...

您正在启动进程,但没有等待它退出。这是来自 the documentation on Execute:

Execute actually executes the program as specified in CommandLine, applying as much as of the specified options as supported on the current platform.

If the poWaitOnExit option is specified in Options, then the call will only return when the program has finished executing (or if an error occured). If this option is not given, the call returns immediatly[sic], but the WaitOnExit call can be used to wait for it to close, or the Running call can be used to check whether it is still running.

你应该在调用Execute之前在options中设置poWaitOnExit选项,这样Execute就会阻塞直到进程退出。或者调用 AProcess.WaitOnExit 显式等待进程退出。