RegisterApplicationRestart with different path - winapi

I have two applications. Both of them use the same resources. Lets call these resources "profile resources". Application B cannot be started up until Application A shutsdown. So I have app A running and was trying to shut it down, then launch up with app B path. I explored RegisterApplicationRestart but I could not accomplish it. Is this possible to be done? I'm getting stuck at the point where Application A is shutdown, then I cant run any code to launch back App B.

A can launch B using CreateProcess() before exiting, passing its own process handle to B. Before B accesses the resource, it can wait on A's handle using WaitForSingleObject() or related function. When the handle is signaled, A has fully terminated, so B can close the handle using CloseHandle() and move on as needed.
To pass A's process handle to B, A can either:
open its own process handle using OpenProcess() with GetCurrentProcessId() as the process ID, mark the handle as inheritable using SetHandleInformation(), and then pass the handle value to B as a command-line parameter, setting the bInheritHandles parameter of CreateProcess() to TRUE.
Run B first and have it create an IPC listener (named pipe, mailslot, socket, etc), then A can duplicate its own process handle for B's use via DuplicateHandle() with GetCurrentProcess() as the source handle and B's process handle (from CreateProcess()) as the target process, then send the duplicate handle value to B via IPC.
A simpler technique is to have A pass its own process ID, rather than its process handle, to B as a command-line parameter, then B can use OpenProcess() to open A's process handle. Although this will usually work, it does have a small race condition - before B has a chance to open the process handle, A might terminate and the OS could reuse its process ID for a new unrelated process, thus B would get a handle to, and wait on, the wrong process.

Related

Is it safe to use a process handle which belongs to a terminated process

I am developing a Windows console application in C++. I need my program to do some operations on another process which I don't have any control over.
But, I have some doubts about a case where the target process might get terminated for some reason (by Task Manager, etc). Is it safe to use a handle to a process which is already terminated?
Note : I stop my operations if one of the functions fails.
HANDLE hProcess = OpenProcess(pid);
if( hProcess != NULL )
{
// Lets suppose process is terminated here
/* Some operations on process using returned handle*/
}
Kernel objects in Windows are reference-counted, with references being represented as handles to objects. Client code can create kernel objects and receive an initial reference (e.g. CreateProcess), increment the reference count on an existing object (e.g. OpenProcess, or DuplicateHandle), and decrement the reference count (CloseHandle). As long as you hold on to a HANDLE, the object referenced by that HANDLE is kept alive.
In case of a process object, that object is valid at least as long as you hold a reference (HANDLE) to it. The fact that a process has been terminated is observable, but doesn't otherwise invalidate or destroy the process object if there are any outstanding references to it.
Specifically this means that you can perform any operations you'd do with a "live" process (one for which the OS is still scheduling threads to execute), such as WaitForSingleObject. In addition you can call GetExitCodeProcess and that call won't return STILL_ACTIVE.
Barring a call to CloseHandle, you are now a stakeholder that has a say in the demise of the process object. It won't go away unless you sign it off. A corollary of this is that you now also control the validity of the PID. It's tied to the process' lifetime, and as long as you hold a reference to it by way of a HANDLE, that PID won't get reused for another process.
In summary, as long as you hold on to a (process) HANDLE you can do whatever.

Use Winapi Sendmessage to retrieve a value from the message's recipient

Given two applications, A and B, B needs to get value from A in a synchronous way.
In other words, taking the object model for inspiration, application B wants to do some kind of myVar = A.getValue() and continue its execution using myVar in the rest of the code.
I have the handle of application A's main form and i know how to send message to it with SendMessage(). This function waits for the message to be proceed and then return an integer that is the result of the execution. But i don't know how to use this mechanism so that B gets back some complex data structure (string or data record).
It seems to me that using the SendMessage return value is not a good idea for many reasons, so is there a way to do that?
It has to be done through Windows Messages (i already know how to do it through pipes and sockets).
Thank you!
PS: i work with Delphi but that has no importance here, unless you are able to give examples in Delphi to illustrate your answer :)
The return value of a message is an LRESULT, that is a pointer sized value. If what you wish to return fits in such a value, that would be the clean way to proceed. Otherwise you need something else.
You say that you must use Windows messages, and that you are sending these messages between different processes. Given those constraints, there is exactly one solution, namely WM_COPYDATA. That is the only Windows message which can marshal custom data across a process boundary.
So the procedure is as follows:
Send a message from process B to process A. Include in that message a window handle from process B.
When process A receives the message, it must send a WM_COPYDATA to the window handle that was sent in stage 1.
Process B can then receive and process the message sent in stage 2.
Note that the WM_COPYDATA message is sent from process A to process B whilst process A is handling the original message. This means that the WM_COPYDATA is received and processed by process B, before the original message from B to A returns. This can be somewhat confusing, but you did state that you wanted to do this entirely with Windows messages.
This can be done by one of your processes performing VirtualAllocEx() to allocate memory in another process and then use Read/WriteProcessMemory to copy data there.

Closehandle() not terminating the process

The process is not getting terminated after closing its handle in CloseHandle().
Well I have a process created by CreateProcess() api. Even after closing Its handle it is still running.
From the msdn, they say that CloseHandle() closes the handle and doesn't terminate process. Have to call terminate thread for that. Then why CloseHandle()?
But when I checked CloseHandle()'s return value, it succeeded. If so I want know what is actually done in this CloseHandle() and why it returns successfully. And I want to know what all operation can be done on the process using its handle. I felt misleading, as CloseHandle() succeeds but the process still runs on!
Would also be great what actually contains in the handle of a process and is there any differences with other type of handles? (file,I/O etc)
Why does closing the handle not terminate the process? Have to call TerminateProcess for that.
Closing the handle does not terminate the process because it would be absurd. Processes generally run independently of each other. If closing the process handle terminated the corresponding process, this wouldn't be the case since when a program exits, all open handles it holds are closed. Which would for example mean that if Explorer crashed, every program you started would be instantly terminated. That would be a desaster, and thus closing the process handle does, by design, not terminate the program.
Terminating a process is almost always a very bad idea. The same goes for terminating a thread. Never do that if you can avoid it. If you want a thread/process to exit, send it a message and wait until it has exited (on its own behalf). This guarantees that data is properly saved and in a consistent state, no resources are leaked, and that no serious conflicts can occur (such as a thread being terminated while it holds a lock).
Terminating threads is often troublesome, and sometimes catastrophic. The same goes for terminating processes. It is only "allowable" to terminate a process or a thread when it is caught in an infinite loop and non-responsive.
Then why do you have to close the handle anyway, and why are you getting one at all if you must close it?
You can do certain things with a handle, among these are for example ReadProcessMemory, WriteProcessMemory, CancelIoEx, running a debugger, use PSAPI, and a few others. Also you can wait on the handle, it will be signalled when the process exits. That is a very simple way of inter-process synchronization.
On the other hand, the operating system cannot release resources as long as you hold the handle open and thus have a "legitimate right" to access these. How can you for example wait for a process, if the process (or at least its structures) does not exist at all any more?
This (and the fact that the handle itself is a resource) is why you should close the handle as soon as possible if you don't need it. Holding it indefinitely requires the OS to keep resources around that are not needed but cannot be freed.
Closing the handle tells the operating system that you don't need it any more, so whenever the OS wants to release all resources associated with the process, it can do so.
What is contained in the process handle?
Like all handles, the process handle is merely an opaque integer that doesn't contain anything. It is an index in a kernel-owned table, technically a void*, but that is only an implementation detail. The actual kernel structure that it refers to is not something you can directly access, not in an easy way anyway.
A handle is a reference to some kernel-managed, reference-counted object. Normally, closing the last handle to an object will result in the destruction of such an object.
But: processes and threads are not killed when closing the last handle, you can think that they "start living on their own" after being started. Without this exception, you couldn't have a process outlive its parent, since each process' handles is closed automatically at process termination (and having a thread outlive its parent would require needless complications).
Anyway, all of this is documented: if you read the documentation of CloseHandle you would have found:
Closing a thread handle does not terminate the associated thread or
remove the thread object. Closing a process handle does not terminate
the associated process or remove the process object. To remove a
thread object, you must terminate the thread, then close all handles
to the thread. For more information, see Terminating a Thread. To
remove a process object, you must terminate the process, then close
all handles to the process. For more information, see Terminating a
Process.
What you described is behavior by design. A process runs on its own, it might have zero or more handles opened, which let their holders control the process in certain ways. Once you hold a handle, you are responsible for closing it.
Termination of the process is a different thing, and you basically are not expected to terminate externally: you never know where exactly you stop the process. You are expected to somehow signal that you want the process termination, so that the process could figure it out and terminate its activity internally, and gracefully.

Question about process access privilege

I got the following scenario:
Process A create process B, and then B try to get a handle of A with OpenProcess(). I want B to have PROCESS_ALL_ACCESS rights to A.
How should I achieve this?
Thanks.
Probably the easiest way is for the parent to avoid the child having to call OpenProcess at all. Instead, have the parent retrieve a handle to itself (which will automatically have all access) and then call DuplicateHandle with bInheritHandle = true. Then when it creates process B, that handle (with full access to process A) will already be open in the child. Process A simply has to pass the handle to process B, and process B can use it.

Windows: Child Process with Redirected Input and Output

I'm trying to create a Child Process with Redirected Input and Output (as described here - http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx).
For the people that don't want to bother reading the source code on that page, the author is using anonymous pipes to redirect the child's input and output. The parent process writes to the child process's input and reads from the child process's output.
In that code however, the program is closing the pipes after reading and writing (in WriteToPipe and ReadFromPipe), so actually the program just reads a file, dumps it on the child process input stream and then reads the child process response.
Now, what I'm looking for is a code where we will not close the pipes, but we will continuously post requests and read the child process response (in contrast to making just 1 request).
I've tried several modifications to the source code given on the link posted above, but no matter what I try, the program always hangs when calling ReadFile() in the ReadFromPipe() function (it probably waits for the child to quit - but as I said I like to get the child response, and then send other requests to it).
Any ideas on how I can get over this?
Update:
Can anyone at least tell me whether using the .NET Process class with RedirectStandardInput and RedirectStandardOutput is a good option?
Had exactly the same problem, and solved it by using PeekNamedPipe (which according to MSDN is also fine for anonymous read pipes) to check for available data before each call to ReadFile. That removed the blocking issues I was getting, and allowed my GetExitCodeProcess() to see that the process had exited and cleanup the pipes.
Yes - the .Net Process class redirects the standard input / output of the child process with anonymous pipes in a very similar way to the linked sample if you use RedirectStandardInput and RedirectStandardOutput, so this is probably a fairly good option.
As for why ReadFile is hanging - it sounds like this function is waiting for the child process to either send some data back, or to close the pipe. If you want to continuously post requests to the child process then you need to either:
Know exactly when it is appropriate to read so that you are not left waiting / blocked for the child process (so for example you only read immediately after a request has been sent). This strategy is very risky as there is always a chance that the child process doesn't behave as expected and you are left waiting on the child process indefinitely.
Have a dedicated thread for reading - if you have a dedicated thread for reading then it doesn't matter that the thread may wait indefinitely for the child process as your other threads are still able to send requests and operate as normal. This method is more complex than the first option, however when done properly is far more robust. The only other drawback to this approach is that it requires you have an additional read thread for each child process, meaning that it doesn't scale very well if you need to communicate with a large number of child processes.
Use asynchronous IO - It is possible to call the ReadFile function in a way such that it always immediately returns, however notifies you when a read has completed (I'm a little fuzzy on the exact details on how this works as I'm more used to C#). This is know as Asynchronous IO and is the most versatile of these 3 methods as it allows you to communicate with many child processes without needing a dedicated thread for each one. The tradeoff however is that it is also the most complex to do correctly (at least in my opinion).

Resources