简体   繁体   English

在C中创建新进程和子进程之间的区别(Windows)

[英]Difference between creating new process and child process in C (Windows)

I would like to create a new process of an exe from within the code itself, so that I can have two parallel processes. 我想从代码本身内部创建一个新的exe进程,以便可以有两个并行进程。

But, I would like to them to be separate processes and not parent-child. 但是,我希望它们是独立的过程,而不是父子过程。

Is there a way to do this in C (Windows)? 有没有办法在C(Windows)中做到这一点?

In Windows, processes don't have parents . 在Windows中, 进程没有父级 Some tools read the InheritedFromUniqueProcessId value, but this does not tell you which process started your process. 一些工具读取InheritedFromUniqueProcessId值,但这不能告诉您哪个进程启动了您的进程。 It only tells you where handles and other attributes were inherited from. 它仅告诉您句柄和其他属性的继承位置。 In practice however, this value is usually set to the ID of the process that started the child process. 但是,实际上,通常将此值设置为启动子进程的进程的ID。

On Vista and above, you can change the InheritedFromUniqueProcessId value by calling CreateProcess with the STARTUPINFOEX structure filled in appropriately: create an attribute list with InitializeProcThreadAttributeList , and add a PROC_THREAD_ATTRIBUTE_PARENT_PROCESS attribute with UpdateProcThreadAttribute . 在Vista或更高版本上,可以通过使用适当填充的STARTUPINFOEX结构调用CreateProcess来更改InheritedFromUniqueProcessId值:使用InitializeProcThreadAttributeList创建属性列表,并使用UpdateProcThreadAttribute添加PROC_THREAD_ATTRIBUTE_PARENT_PROCESS属性。

On XP, there is no official way of doing this. 在XP上,没有官方的方法可以做到这一点。 You can try to use NtCreateProcess or RtlCreateUserProcess , but these don't set up the Win32 subsystem properly so your program might not run. 您可以尝试使用NtCreateProcessRtlCreateUserProcess ,但是它们不能正确设置Win32子系统,因此您的程序可能无法运行。

An ugly way I've done it in the past is to launch a child process, which then launches a second child process, and then the first child exits. 我过去做的一个丑陋方法是启动一个子进程,然后启动第二个子进程,然后第一个子进程退出。 This causes the second child to lose any association with the original parent. 这导致第二个孩子失去与原始父母的任何关联。

I'm sure I later found a better way to do this, but I've gone looking around and can't find anything at the moment. 我确定以后会找到更好的方法,但是我已经四处张望,目前找不到任何东西。

最有可能的fork荷兰国际集团一个新的进程并不存在于Windows,而你可以使用CreateProcess的功能,这样做是为Windows更容易和更好的选择。

The "easy" way is to use an intermediate command, see KB here: “简便”的方法是使用中间命令,请参见此处的知识库:

http://support.microsoft.com/kb/315939 http://support.microsoft.com/kb/315939

Another way to have independent processes is to ensure to do not inherit handles to ensure that the 2nd process, and creating a new process group. 具有独立流程的另一种方法是确保不继承句柄以确保第二个流程,并创建一个新的流程组。 See Creating independent process! 请参阅创建独立的流程!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM