系统命令执行但立即后台 [英] System command executes but is immediately backgrounded

查看:89
本文介绍了系统命令执行但立即后台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用TProcess单元执行ssh以连接到我的一台服务器并为我提供外壳.这是我在Ruby中的一个重写,因为Ruby的执行时间很慢.当我运行Process.Execute函数时,会看到shell,但它会立即背景化.运行pgrep ssh表示它正在运行,但是无论如何我都无法访问它,使用fg不会恢复它.该段的代码如下:

I'm attempting to use the TProcess unit to execute ssh to connect to one of my servers and provide me with the shell. It's a rewrite of one I had in Ruby as the execution time for Ruby is very slow. When I run my Process.Execute function, I am presented with the shell but it is immediately backgrounded. Running pgrep ssh reveals that it is running but I have no access to it whatsoever, using fg does not bring it back. The code is as follows for this segment:

  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;

TempFile是类型为TProfile的变量,该变量是包含有关服务器信息的记录.编目系统和检索工作正常,但拉起外壳则不行.

TempFile is a variable of type TProfile, which is a record containing information about the server. The cataloging system and retrieval works fine, but pulling up the shell does not.

推荐答案

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

您正在开始该过程,但不等待其退出.这来自 Execute 上的文档:

You're starting the process but not waiting for it to exit. This is from the documentation on Execute:

Execute实际上执行CommandLine中指定的程序,并应用当前平台所支持的尽可能多的指定选项.

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

如果在选项"中指定了poWaitOnExit选项,则仅当程序执行完毕(或发生错误)时,调用才会返回. 如果未指定此选项,则调用会立即返回 [sic],但是可以使用WaitOnExit调用来等待它关闭,或者可以使用Running调用来检查它是否仍在运行

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之前在选项中设置poWaitOnExit选项,以便Execute将阻塞,直到进程退出.否则,调用AProcess.WaitOnExit明确等待进程退出.

You should set the poWaitOnExit option in options before calling Execute, so that Execute will block until the process exits. Or else call AProcess.WaitOnExit to explicitly wait for the process to exit.

这篇关于系统命令执行但立即后台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆