I would like to know if it's possible to run a command and get its exit code. I have seen that it's possible to capture the stdout of the process, but I have not found anything about the exit code. Is it possible to do this on Linux?
Delphi version: 10.4
OS: Ubuntu 18.04
This is the unit I use to run the command and get its output:
unit TestRunCommand;
interface
uses
System.SysUtils,
Posix.Base,
Posix.Fcntl;
type
TStreamHandle = pointer;
function popen(const command: MarshaledAString; const _type: MarshaledAString): TStreamHandle; cdecl; external libc name _PU + 'popen';
function pclose(filehandle: TStreamHandle): int32; cdecl; external libc name _PU + 'pclose';
function fgets(buffer: pointer; size: int32; Stream: TStreamHandle): pointer; cdecl; external libc name _PU + 'fgets';
function RunCommand(const acommand: MarshaledAString): String; forward;
implementation
function RunCommand(const acommand: MarshaledAString): String;
// run a linux shell command and return output
var
handle: TStreamHandle;
data: array [0 .. 511] of uint8;
function bufferToString(buffer: pointer; maxSize: uint32): string;
var
cursor: ^uint8;
endOfBuffer: nativeuint;
begin
if not assigned(buffer) then
exit;
cursor := buffer;
endOfBuffer := nativeuint(cursor) + maxSize;
while (nativeuint(cursor) < endOfBuffer) and (cursor^ <> 0) do
begin
result := result + chr(cursor^);
cursor := pointer(succ(nativeuint(cursor)));
end;
end;
begin
result := '';
handle := popen(acommand, 'r');
try
while fgets(@data[0], sizeof(data), handle) <> nil do
begin
result := bufferToString(@data[0], sizeof(data));
end;
finally
pclose(handle);
end;
end;
end.