Jump to content

How to attach child process to other external process?


Recommended Posts

Hi,

My question today is how can we attach some executed application to other process?

What i mean is that when we use Run() (for example), the execute process is become to be a child process, what i need is to "tell" to that process that his parent is not my script, but some other process, for example «MyOtherApp.exe». Is that would be possible to do?

Thanks.

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Hi,

My question today is how can we attach some executed application to other process?

What i mean is that when we use Run() (for example), the execute process is become to be a child process, what i need is to "tell" to that process that his parent is not my script, but some other process, for example «MyOtherApp.exe». Is that would be possible to do?

Thanks.

I don't know much about this, but are you sure the executed process is a child? With Gui creation for example if you create a child window then the child is destroyed when the parent is destroyed. But if you have

$cmdPID = Run("cmd", "", @SW_SHOWNORMAL);

then the script will end as soon as the command prompt window appears but the command prompt window stays. So if the script was the parent of the process what is the parent when the script has finished?

If it's a window that is created then you can change the parent with the SetParent API.

I would have guessed that all processes which are not child windows were 'children' of the Process Manager.

(Hoping I can learn something here.)

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

are you sure the executed process is a child?

Yes, it is a child until the parent process exists...

if the script was the parent of the process what is the parent when the script has finished?

The system :) - I am using Process Explorer, and there you can see details about the process, and in the Threads tab (properties window for the process) you can see that the parent is actualy him self muttley .

Here is an example that shows what the parent:

;We check if it's a first run, then we execute the notepad
If Not StringInStr($CmdLineRaw, "/PID=") Then
    $iPID = Run('Notepad.exe')
    
    ;Here we run the script again with extra parameter passing the Notpad's PID
    Run(@AutoItExe & ' /AutoIt3ExecuteScript "' & @ScriptFullPath & '" /PID=' & $iPID)
    Exit
Else
    $iPID = StringRegExpReplace($CmdLineRaw, ".*?/PID=(.*?)$", "\1")
EndIf

;Now we run in other process to check the child PID that is no longer a child :)
$iParentPID = _GetParentPID($iPID)

MsgBox(0, 'ParentID', _
    'Application: Notepad' & @CRLF & _
    'Application PID: ' & $iPID & @CRLF & _
    'Application Parent PID: ' & $iParentPID & @CRLF & _
    'Application Parent FilePath: ' & _ProcessGetPath($iParentPID))

ProcessClose($iPID)

Func _GetParentPID($iPID)
    Local $wbemFlagReturnImmediately = 0x10
    Local $wbemFlagForwardOnly = 0x20
    Local $colItems = ""
    Local $strComputer = "localhost"
    
    $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
    $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_Process", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

    If IsObj($colItems) Then
        For $objItem In $colItems
            If $objItem.ProcessId = $iPID Then Return $objItem.ParentProcessId
        Next
    Endif
    
    Return ''
EndFunc

Func _ProcessGetPath($vProcess)
    Local $iPID = ProcessExists($vProcess)
    If Not $iPID Then Return SetError(1, 0, -1)
    
    Local $aProc = DllCall('kernel32.dll', 'hwnd', 'OpenProcess', 'int', BitOR(0x0400, 0x0010), 'int', 0, 'int', $iPID)
    If Not IsArray($aProc) Or Not $aProc[0] Then Return SetError(2, 0, -1)
    
    Local $vStruct = DllStructCreate('int[1024]')
    
    Local $hPsapi_Dll = DllOpen('Psapi.dll')
    If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@SystemDir & '\Psapi.dll')
    If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@WindowsDir & '\Psapi.dll')
    If $hPsapi_Dll = -1 Then Return SetError(3, 0, '')
    
    DllCall($hPsapi_Dll, 'int', 'EnumProcessModules', _
        'hwnd', $aProc[0], _
        'ptr', DllStructGetPtr($vStruct), _
        'int', DllStructGetSize($vStruct), _
        'int_ptr', 0)
    Local $aRet = DllCall($hPsapi_Dll, 'int', 'GetModuleFileNameEx', _
        'hwnd', $aProc[0], _
        'int', DllStructGetData($vStruct, 1), _
        'str', '', _
        'int', 2048)
    
    DllClose($hPsapi_Dll)
    
    If Not IsArray($aRet) Or StringLen($aRet[3]) = 0 Then Return SetError(4, 0, '')
    Return $aRet[3]
EndFunc

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Yes, it is a child until the parent process exists...

The system :) - I am using Process Explorer, and there you can see details about the process, and in the Threads tab (properties window for the process) you can see that the parent is actualy him self muttley .

Here is an example that shows what the parent:

.

.

Thanks for that example MrCreatoR. I tried changing your example to help my understanding of this and my version doesn't seem to work. Can you see what I'm doing wrong?

;We check if it's a first run, then we execute the notepad
If Not StringInStr($CmdLineRaw, "/PID=") Then
    $iPID = Run('Notepad.exe')
    $title = 'First Application'
;Here we run the script again with extra parameter passing the Notpad's PID
    Run(@AutoItExe & ' /AutoIt3ExecuteScript "' & @ScriptFullPath & '" /PID=' & $iPID)
    While 1
        Sleep(200)
    WEnd
Else
    
    $iPID = StringRegExpReplace($CmdLineRaw, ".*?/PID=(.*?)$", "\1")
EndIf

;Now we run in other process to check the child PID that is no longer a child smile.gif
$iParentPID = _GetParentPID($iPID)
$title = 'First Application'

$caption1 = $title & ': Notepad' & @CRLF & _
        $title & ' PID: ' & $iPID & @CRLF & _
        $title & ' Parent PID: ' & $iParentPID & @CRLF & _
        $title & ' Parent FilePath: ' & _ProcessGetPath($iParentPID) & @CRLF & _
        $title & ' Script PID:' & @AutoItPID


ProcessClose($iParentPID)
While ProcessExists($iParentPID)
    Sleep(100)
WEnd

;Sleep(1000)
$iParentPID = _GetParentPID($iPID);looks like the return is wrong here
$title = 'Second Application'
$caption2 = $title & ': Notepad' & @CRLF & _
        $title & ' PID: ' & $iPID & @CRLF & _
        $title & ' Parent PID: ' & $iParentPID & @CRLF & _
        $title & ' Parent FilePath: ' & _ProcessGetPath($iParentPID) & @CRLF & _
        $title & ' Script PID:' & @AutoItPID

MsgBox(0, 'ParentID', $caption1 & @CRLF & $caption2)
ProcessClose($iPID)

Func _GetParentPID($iPID)
    Local $wbemFlagReturnImmediately = 0x10
    Local $wbemFlagForwardOnly = 0x20
    Local $colItems = ""
    Local $strComputer = "localhost"

    $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
    $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_Process", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

    If IsObj($colItems) Then
        For $objItem In $colItems
            If $objItem.ProcessId = $iPID Then Return $objItem.ParentProcessId
        Next
    EndIf

    Return ''
EndFunc  ;==>_GetParentPID

Func _ProcessGetPath($vProcess)
    Local $iPID = ProcessExists($vProcess)
    If Not $iPID Then Return SetError(1, 0, -1)

    Local $aProc = DllCall('kernel32.dll', 'hwnd', 'OpenProcess', 'int', BitOR(0x0400, 0x0010), 'int', 0, 'int', $iPID)
    If Not IsArray($aProc) Or Not $aProc[0] Then Return SetError(2, 0, -1)

    Local $vStruct = DllStructCreate('int[1024]')

    Local $hPsapi_Dll = DllOpen('Psapi.dll')
    If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@SystemDir & '\Psapi.dll')
    If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@WindowsDir & '\Psapi.dll')
    If $hPsapi_Dll = -1 Then Return SetError(3, 0, '')

    DllCall($hPsapi_Dll, 'int', 'EnumProcessModules', _
            'hwnd', $aProc[0], _
            'ptr', DllStructGetPtr($vStruct), _
            'int', DllStructGetSize($vStruct), _
            'int_ptr', 0)
    Local $aRet = DllCall($hPsapi_Dll, 'int', 'GetModuleFileNameEx', _
            'hwnd', $aProc[0], _
            'int', DllStructGetData($vStruct, 1), _
            'str', '', _
            'int', 2048)

    DllClose($hPsapi_Dll)

    If Not IsArray($aRet) Or StringLen($aRet[3]) = 0 Then Return SetError(4, 0, '')
    Return $aRet[3]
EndFunc  ;==>_ProcessGetPath
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

I tried changing your example to help my understanding of this and my version doesn't seem to work. Can you see what I'm doing wrong?

I am not sure what are you trying to do... but still that's strange to me, in both captions the parent PID is the same, how it can be if in the second caption we destroyed the parent process, but the _ProcessGetPath() function return -1, and it's correct because that process not exists anymore...

It seems that even if the parent process destroyed, the child process have the information about his initial parent.

Btw: You are using a loop to wait untill the process is closed, but you can use just ProcessWaitClose() muttley

P.S

Somebody have an ideas on the topic's issue? is it possible at least?

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

I am not sure what are you trying to do... but still that's strange to me, in both captions the parent PID is the same, how it can be if in the second caption we destroyed the parent process, but the _ProcessGetPath() function return -1, and it's correct because that process not exists anymore...

I wanted to show the parent PID while the parent still existed then see what the parent became after the parent was destroyed. Some of what I did was nonsense so I need to think it out again.

Btw: You are using a loop to wait untill the process is closed, but you can use just ProcessWaitClose()

Yes that would have been better.
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

Hi,

My question today is how can we attach some executed application to other process?

After reading this on msdn I would expect that you cannot change the parent precess.

ParentProcessId

Data type: uint32

Access type: Read-only

Unique identifier of the process that creates a process. Process identifier numbers are reused, so they only identify a process for the lifetime of that process. It is possible that the process identified by ParentProcessId is terminated, so ParentProcessId may not refer to a running process. It is also possible that ParentProcessId incorrectly refers to a process that reuses a process identifier. You can use the CreationDate property to determine whether the specified parent was created after the process represented by this Win32_Process instance was created.

from here

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...