Hi Andrew,
Would you mind if I put that program up on the wiki as an example?
Thanks,
BigChimp
I'd modify it to something like this (compiles, but not tested on Linux/OSX):
program rootls;
{ Demonstrates using TProcess, redirecting stdout/stderr to our stdout/stderr,
calling sudo on Linux/OSX, and supplying input on stdin}
{$mode objfpc}{$H+}
uses
Classes,
Math, {for min}
Process;
procedure RunsLsRoot;
var
Proc: TProcess;
CharBuffer: array [0..511] of char;
RestCount: integer;
ExitCode: integer;
SudoPassword: string;
begin
WriteLn('Please enter the sudo password:');
Readln(SudoPassword);
ExitCode := -1; //Start out with failure, let's see later if it works
Proc := TProcess.Create(nil); //Create a new process
try
Proc.Options := [poUsePipes]; //Use pipes to redirect program stdin,stdout,stderr
Proc.CommandLine := 'sudo -S ls /root'; //Run ls /root as root using sudo
// -S causes sudo to read the password from stdin.
Proc.Execute; //start it. sudo will now probably ask for a password
// write the password to stdin of sudo
SudoPassword := SudoPassword + LineEnding;
Proc.Input.Write(SudoPassword[1], Length(SudoPassword));
SudoPassword := 'password'; //hope this will scramble memory
SudoPassword := ''; // and make the program a bit safer from snooping?!?
// main loop to read output from stdout and stderr of sudo
while Proc.Running or (Proc.Output.NumBytesAvailable > 0) or
(Proc.Stderr.NumBytesAvailable > 0) do
begin
// read stdout and write to our stdout
while Proc.Output.NumBytesAvailable > 0 do
begin
RestCount := Min(512, Proc.Output.NumBytesAvailable); //Read up to buffer, not more
Proc.Output.Read(CharBuffer, RestCount);
Write(StdOut, Copy(CharBuffer, 0, RestCount));
end;
// read stderr and write to our stderr
while Proc.Stderr.NumBytesAvailable > 0 do
begin
RestCount := Min(512, Proc.Stderr.NumBytesAvailable); //Read up to buffer, not more
Proc.Stderr.Read(CharBuffer, RestCount);
Write(StdErr, Copy(CharBuffer, 0, RestCount));
end;
end;
ExitCode := Proc.ExitStatus;
finally
Proc.Free;
Halt(ExitCode);
end;
end;
begin
RunsLsRoot;
end.