Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Command Line Arguments of Another Process (Win32 C code)

Tags:

python

c

winapi

I need to be able to list the command line arguments (if any) passed to other running processes. I have the PIDs already of the running processes on the system, so basically I need to determine the arguments passed to process with given PID XXX.

I'm working on a core piece of a Python module for managing processes. The code is written as a Python extension in C and will be wrapped by a higher level Python library. The goal of this project is to avoid dependency on third party libs such as the pywin32 extensions, or on ugly hacks like calling 'ps' or taskkill on the command line, so I'm looking for a way to do this in C code.

I've Googled this around and found some brief suggestions of using CreateRemoteThread() to inject myself into the other process, then run GetCommandLine() but I was hoping someone might have some working code samples and/or better suggestions.

UPDATE: I've found full working demo code and a solution using NtQueryProcessInformation on CodeProject: http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx - It's not ideal since it's "unsupported" to cull the information directly from the NTDLL structures but I'll live with it. Thanks to all for the suggestions.

UPDATE 2: I managed through more Googling to dig up a C version that does not use C++ code, and is a little more direct/concisely pointed toward this problem. See http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/ for details.

Thanks!

like image 493
Jay Avatar asked Jan 13 '09 21:01

Jay


1 Answers

To answer my own question, I finally found a CodeProject solution that does exactly what I'm looking for:

http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx

As @Reuben already pointed out, you can use NtQueryProcessInformation to retrieve this information. Unfortuantely it's not a recommended approach, but given the only other solution seems to be to incur the overhead of a WMI query, I think we'll take this approach for now.

Note that this seems to not work if using code compiled from 32bit Windows on a 64bit Windows OS, but since our modules are compiled from source on the target that should be OK for our purposes. I'd rather use this existing code and should it break in Windows 7 or a later date, we can look again at using WMI. Thanks for the responses!

UPDATE: A more concise and C only (as opposed to C++) version of the same technique is illustrated here:

http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/

like image 106
Jay Avatar answered Oct 21 '22 13:10

Jay