简体   繁体   English

当进程(父进程和子进程)在同一代码上工作时,使用fork()系统调用有什么意义?

[英]What is the point in using fork() system call when both the processes (parent and child) work on the same code?

I read that the parent and the child will work on the identical code after the fork() system call. 我读到父和子将在fork()系统调用之后处理相同的代码。 I cannot understand the point of doing a fork() as I cannot understand what good will it do in executing the same code twice. 我无法理解做fork()因为我无法理解它在执行两次相同代码时会有什么用处。

The return value of fork() is different in the child and parent processes, so you'll typically have something along the lines of fork()的返回值在子进程和父进程中是不同的,因此您通常会有类似的东西

pid_t child_pid = fork()
if (child_pid == 0) {
  // do stuff in child process
} else {
  // do stuff in parent process
}

You can use an if else condition to execute different piece of code for parent and child. 您可以使用if else条件为父级和子级执行不同的代码。 As fork returns 0 to the child process and it returns pid of the child to the parent. fork将0返回到子进程,并将子进程的pid返回给父进程。 Use this as the differentator in the if condition. 在if条件下使用它作为差异器。

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

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