当两个进程(父进程和子进程)在同一代码上工作时,使用 fork() 系统调用有什么意义?
What is the point in using fork() system call when both the processes (parent and child) work on the same code?
我读到在 fork()
系统调用后父子将处理相同的代码。我无法理解执行 fork()
的意义,因为我无法理解将相同的代码执行两次有什么好处。
fork()
的 return 值在子进程和父进程中是不同的,因此您通常会有类似
的内容
pid_t child_pid = fork()
if (child_pid == 0) {
// do stuff in child process
} else {
// do stuff in parent process
}
您可以使用 if else 条件为父项和子项执行不同的代码段。因为 fork returns 0 到子进程,它 returns 子进程的 pid 到父进程。在 if 条件中使用它作为微分器。
我读到在 fork()
系统调用后父子将处理相同的代码。我无法理解执行 fork()
的意义,因为我无法理解将相同的代码执行两次有什么好处。
fork()
的 return 值在子进程和父进程中是不同的,因此您通常会有类似
pid_t child_pid = fork()
if (child_pid == 0) {
// do stuff in child process
} else {
// do stuff in parent process
}
您可以使用 if else 条件为父项和子项执行不同的代码段。因为 fork returns 0 到子进程,它 returns 子进程的 pid 到父进程。在 if 条件中使用它作为微分器。