在 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:~$
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP