如何从单个父级创建两个进程 [英] how to create two processes from a single Parent
问题描述
我知道我将需要使用fork(),但这只会创建一个子进程.我是否只是在子进程中再次调用fork?另外,我需要它们通过信号或管道进行通信,这更易于实现,并且我需要知道些什么(功能等).
I know I'm going to need to use fork(), but this just creates a single child process. Do i simply call fork again from within the child process? Also, I need them to communicate through a signal or pipe, which is easier to implement and what do i need to know for doing that (functions, etc..)
推荐答案
要创建第二个进程,请再次调用fork()
-在父级或子级中(但不能同时使用!).选择哪种选择取决于您是希望此进程是原始父进程的子进程还是第一个子进程的子进程(通常是原始父进程的子进程).
To create a second process, call fork()
again - either within the parent or the child (but not both!). Which you choose depends on whether you want this process to be a child of the original parent or a child of the first child process (it is usual for it to be a child of the original parent).
通过管道进行通信比使用信号更简单,更可靠. pipe()
,close()
,read()
,write()
和select()
是此处的主要功能.
Communicating through a pipe is much simpler and more reliable than using signals. pipe()
, close()
, read()
, write()
and select()
are the key functions here.
例如,要让父级创建两个子进程,您可以执行以下操作:
For example, to have the parent create two child processes, you would do something like:
pid_t child_a, child_b;
child_a = fork();
if (child_a == 0) {
/* Child A code */
} else {
child_b = fork();
if (child_b == 0) {
/* Child B code */
} else {
/* Parent Code */
}
}
这篇关于如何从单个父级创建两个进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!