nikitablack
nikitablack

Reputation: 4663

How to run a process with ShellExecuteEx as as a child that closes after parent exit?

I need to spawn a process which need to invoke UAC. I have read this post: How can I run a child process that requires elevation and wait?.

Unfortunatelly I can't run a process as a real child. The new process run as a separate and continue to run even after spawner close. But I need it to close automatically when parent exits (normal exit or by crash or any other reason).

One of the solution that were provided is to use jobs for that. Unfortunately I can't assign a process created with ShellExecuteEx to a job. It returns me an error ERROR_ACCESS_DENIED. To handle this I have to pass CREATE_BREAKAWAY_FROM_JOB to CreateProcess. And this is the closed circle. I have to use ShellExecuteEx but not CreateProcess.

Upvotes: 2

Views: 3101

Answers (1)

David Heffernan
David Heffernan

Reputation: 612993

You have the use the shell verb runas to force elevation. Which rules out CreateProcess. So you can do the following:

  1. Use ShellExecuteEx to create the child process.
  2. Arrange for ShellExecuteEx to return a process handle for the child.
  3. When the parent terminates, terminate the child.

If you want to use jobs to tie the processes lives together then you need to include the requiresAdministrator manifest option of the child. That way you can use CreateProcess and specify the process creation flags as you desire.

Now, you may wish not to have the child process manifested that way. If so then you can still get the job done with a call to CreateProcess. You need three processes:

  • Parent process, runs as standard user.
  • Launcher process, manifested to be elevated. Created by parent, with appropriate job flags, and passed arguments that specify how to launch child. Which it does with CreateProcess and placed in same job.
  • Child process. Not manifested to be elevated. But because it is launched by the elevated launcher it too is elevated.

The point here is that there are two ways to force elevation. Statically at compile time with a manifest. That allows you to use CreateProcess. Or dynamically with the runas shell verb. That forces ShellExecuteEx. You state that you are pushed to CreateProcess, and so that means the use of a manifest to force elevation.

Upvotes: 3

Related Questions