IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage Delphi Discussion :

Creation de process


Sujet :

Langage Delphi

  1. #1
    Nouveau membre du Club
    Inscrit en
    Juillet 2008
    Messages
    71
    Détails du profil
    Informations personnelles :
    Âge : 40

    Informations forums :
    Inscription : Juillet 2008
    Messages : 71
    Points : 32
    Points
    32
    Par défaut Creation de process
    Bonjour,

    j'ai créé un objet permettant de lancer une application. Celui ci créé le process puis va lire son état à chaque top d'un timer. Des événements sont associés:
    -A chaque top du timer, quand l'appli est toujours active.
    -A la fin de l'execution, si tout s'est bien déroulé.
    Il est également possible de passer en paramètre un Tmemo et/ou un nom de fichier pour la redirection stdout.

    Le problème est le suivant:
    1) Je créé mon objet
    2)Je l'utilise une premiere fois pour une premiere commande
    --> tout se passe bien
    3)Aprés la fin de la 1ere commande, je l'utilise pour une 2 eme commande
    -->Le process est bien créé
    -->Les processId et Handle sont bien ceux que je peux retrouver dans le gestionnaire de tache ou Process Explorer
    -->Mais quand au premier top de mon timer, je regarde l'etat du process grace a GetExitCodeProcess(hProcess, ExitCode), la fonction echoue et me retourne l'erreur idientifiant invalid... alors que le handle existe bien.

    Quelqu'un aurait-il une idée?
    J'ai tout essayé, j'ai tout retourné dans tous les sens mais la j'avoue que je suis largué.

    Voici mon code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
     
    unit Unite_Process_Launcher;
     
    interface
    Uses Windows,StdCtrls,ExtCtrls, SysUtils, Forms, Tlhelp32, dialogs;
     
    Type
      TProcedure    = procedure of object;
     
      TProcLauncher = class
      private
        { Déclarations privées }
        FOutMemo    : TMemo;
        FOutFileName: String;
        FOnExit     : TProcedure;
        FOnTimer    : TProcedure;
     
        Timer              : TTimer;
        ReadPipe,WritePipe : THandle;
        Proc_Info          : TProcessInformation;
     
        procedure Timer_OnTimer(Sender: TObject);
        procedure writeLog;
        procedure killAllProcessesFrom(procId: DWORD);
        function  Is_busy: boolean;
      public
        { Déclarations publiques }
        Constructor Create;
        Function    Execute(Cmd             : String;
                            params          : String;
                            title           : String;
                            CheckInterval   : Cardinal;
                            OnTimer         : TProcedure;
                            OnExit          : TProcedure;
                            Outmemo     : TMemo;
                            OutFileName : String): Boolean;
     
        property    Busy: boolean read is_Busy;
      end;
     
     
    implementation
     
    { TProcLauncher }
     
    {-----------------------------------------------------------------------
     -----------------------------------------------------------------------}
    constructor TProcLauncher.Create;
    begin
      Timer := TTimer.create(nil);
      Timer.enabled:=false;
      Timer.OnTimer:=Timer_OnTimer;
    end;
     
    {-----------------------------------------------------------------------
     Execute une commande
     Cmd           : La Commande
     Params        : Les parametres
     Title         : Le titre
     CheckInterval : Interval de temps entre chaque verification d'etat
     OnTimer       : Evenement sur chaque interval (Nil si inutile)
     OnExit        : Evenement à la fin de l'execution du process (Nil si inutile)
     Outmemo       : Redirection en sortie du prcess vers un TMemo (Nil si inutile)
     OutFileName   : Redirection en sortie du prcess vers un fichier log ('' si inutile)
     -----------------------------------------------------------------------}
    Function TProcLauncher.Execute(Cmd, params,title: String; CheckInterval: Cardinal;
      OnTimer,OnExit: Tprocedure; Outmemo: TMemo; OutFileName: String): Boolean;
    var
     Security           : TSecurityAttributes;
     startinfo          : TStartUpInfo;
    begin
      result:=false;
      if busy then exit; // un process est deja en cours
      {Initialisation}
      if checkinterval>0 then Timer.Interval:=CheckInterval
      else Timer.Interval:=3000;
      Foutmemo      :=OutMemo;
      FoutFilename  :=OutFileName;
      FOnExit       :=OnExit;
      FOnTimer      :=Ontimer;
     
      With Security do begin
        nlength := SizeOf(TSecurityAttributes) ;
        binherithandle := true;
        lpsecuritydescriptor := nil;
      end;
     
      if Createpipe (ReadPipe, WritePipe,@Security, 0) then
      begin
       FillChar(proc_info, sizeof(TProcessInformation), #0);
       FillChar(startinfo, sizeof(TStartupInfo), #0);
       startinfo.cb := sizeof(TStartupInfo);
       startinfo.hStdOutput := WritePipe;
       startinfo.hStdInput := ReadPipe;
       startinfo.&dwFlags := STARTF_USESTDHANDLES+StartF_USESHOWWINDOW;
       startinfo.wShowWindow := SW_HIDE;
       startinfo.lpTitle:= PANSICHAR(Title);
     
       if CreateProcess(nil,PANSICHAR(cmd+params),@Security,@Security,
                        true,CREATE_DEFAULT_ERROR_MODE
                        + NORMAL_PRIORITY_CLASS, nil, nil,
                        startinfo,proc_info) then
       Begin
         Timer.enabled:=true;  //Timer attend la fin de process
         result:=true;
       End;
     End;
     
     if Result=false then
     Begin
       CloseHandle(proc_info.hProcess);
       CloseHandle(proc_info.hThread) ;
       CloseHandle(ReadPipe) ;
       CloseHandle(WritePipe);
     End;
    end;
     
    function TProcLauncher.Is_busy: boolean;
    begin
      result:=timer.enabled;
    end;
     
     
    {-----------------------------------------------------------------------
     A chaque top du timer, on met à jour le log et on regarde l'etat du process
     -----------------------------------------------------------------------}
    procedure TProcLauncher.Timer_OnTimer(Sender: TObject);
    var
     ExitCode: LongWord;
    begin
      Timer.Enabled := False;
      writeLog;
      {Action suivant etat}
      Application.ProcessMessages;
      if GetExitCodeProcess(proc_info.hProcess, ExitCode) then
      Begin
        if ExitCode = STILL_ACTIVE
        then
        begin
          if assigned(FOnTimer) then FOntimer;
          Timer.Enabled := True
        end
        else
        begin
          if assigned(FOnExit) then FOnExit;
          CloseHandle(proc_info.hProcess);
          CloseHandle(proc_info.hThread) ;
          CloseHandle(ReadPipe) ;
          CloseHandle(WritePipe) ;
        end;
      end
      else
      begin
          ShowMessage(SysErrorMessage(GetLastError));
     
          if assigned(FOnExit) then FOnExit;
          CloseHandle(proc_info.hProcess);
          CloseHandle(proc_info.hThread) ;
          CloseHandle(ReadPipe) ;
          CloseHandle(WritePipe) ;
      end;
    end;
     
    {-----------------------------------------------------------------------
     Redirection de ReadPipe vers le Memo log et/ou le fichier log
     -----------------------------------------------------------------------}
    procedure TProcLauncher.writeLog;
    const
      ReadBuffer = 2400;
    var
      BytesRead : DWord;
      Buffer    : Pchar;
      OutFile   : TextFile;
    begin
       Buffer := AllocMem(ReadBuffer + 1) ;
       Repeat
        BytesRead := 0;
        ReadFile(ReadPipe,Buffer[0],ReadBuffer,BytesRead,nil) ;
        Buffer[BytesRead]:= #0;
        OemToAnsi(Buffer,Buffer) ;
        {Memo Log}
        If FOutMemo<>Nil then FOutMemo.Text := FOutMemo.text + String(Buffer)  ;
        {Fichier Log}
        If FOutFileName<>'' then
        Begin
         try
           assignfile(outFile,FoutFilename);
           If FileExists(FOutFileName) then append(OutFile)
           else rewrite(OutFile);
           write(OutFile,String(Buffer));
           closeFile(OutFile);
         Except
           FOutFileName:='';
         end;
        End;
       until (BytesRead < ReadBuffer) ;
      FreeMem(Buffer);
    end;
     
    end.

  2. #2
    Nouveau membre du Club
    Inscrit en
    Juillet 2008
    Messages
    71
    Détails du profil
    Informations personnelles :
    Âge : 40

    Informations forums :
    Inscription : Juillet 2008
    Messages : 71
    Points : 32
    Points
    32
    Par défaut
    Problème résolu.

    J'appelle mon deuxième processus dans le FOnExit du premier.
    Il faut donc que la libération des Handles se fasse avant le FOnExit.
    Sinon les handles libérés sont ceux du deuxième process, donc au premier top du timer, les Handles n'existent plus.

    C'était juste ça!

    Voici le nouveau code pour la procedure OnTimer

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
     
    procedure TProcLauncher.Timer_OnTimer(Sender: TObject);
    var
     ExitCode: LongWord;
    begin
      Timer.Enabled := False;
      writeLog;
      {Action suivant etat}
      if GetExitCodeProcess(proc_info.hProcess, ExitCode) then
      Begin
        if ExitCode = STILL_ACTIVE
        then
        begin
          if assigned(FOnTimer) then FOntimer;
          Timer.Enabled := True
        end
        else
        begin
          FreeHandles;
          if assigned(FOnExit) then FOnExit;
     
        end;
      end
      else
      begin
          If getlasterror>0 then
          ShowMessage(SysErrorMessage(GetLastError));
          FreeHandles;
          if assigned(FOnExit) then FOnExit;
     
      end;
    end;

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Creation d'un Pool de process[Débutant]
    Par Ghurdyl dans le forum Windows Forms
    Réponses: 0
    Dernier message: 15/09/2009, 10h33
  2. Probleme de creation d'un process project
    Par edogawa dans le forum Wildfly/JBoss
    Réponses: 0
    Dernier message: 18/05/2009, 02h43
  3. API/Library pour creation de process
    Par Johan.Mazel dans le forum C++
    Réponses: 7
    Dernier message: 21/01/2009, 19h37
  4. Creation de fiche dynamique
    Par Mouss26 dans le forum C++Builder
    Réponses: 7
    Dernier message: 24/07/2002, 07h56
  5. Creation d une clee dans la registry en VC++
    Par rico27fr dans le forum MFC
    Réponses: 4
    Dernier message: 30/05/2002, 12h36

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo