在 C 中使用 `fork()` 创建多个进程


在本节中,我们将了解如何在 C 中使用 `fork()` 来生成子进程。我们还在每个进程中执行一些不同的任务。因此,在我们的父进程中,我们将打印不同的值。

调用 `fork()` 时,它会返回一个值。如果该值大于 0,则当前在父进程中,否则在子进程中。因此,使用此方法,我们可以区分这些进程。

示例代码

#include <stdio.h>
#include <unistd.h>
int main() {
   int n = fork(); //subdivide process
   if (n > 0) { //when n is not 0, then it is parent process
      printf("Parent process 
";    } else { //when n is 0, then it is child process       printf("Child process
");    }    return 0; }

输出

soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
Parent process
soumyadeep@soumyadeep-VirtualBox:~$ Child process
soumyadeep@soumyadeep-VirtualBox:~$

更新日期:30-Jul-2019

2K+ 浏览量

启动你的 职业

完成课程获得认证

开始学习
广告
© . All rights reserved.