System command executes but is immediately backgrounded

末鹿安然 提交于 2020-01-06 03:32:05

问题


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 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.


回答1:


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

You're starting the process but not waiting for it to exit. This is from 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.

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.



来源:https://stackoverflow.com/questions/32366090/system-command-executes-but-is-immediately-backgrounded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!