fork() 4 children 循环
fork() 4 children in a loop
目标是尝试在一个循环中分叉 4 children,但我不确定如何正确地做到这一点。这是我到目前为止所拥有的。我试着把它画出来,我想我已经等不及要好好收割 child 了。我每次迭代都会创建 2 children。所以一共8children.
void main() {
int i = 0;
pid_t pid;
int status;
for(i = 0; i < 4; i++) {
pid = fork();
if(pid == 0) {
/* Child Process */
fork();
exit(0);
} else {
/* Parent Process */
wait(&status);
printf("At i = %d, process %d is terminated.\n", i, pid);
}
}
}
从同一个 parent 进程创建四个 children 进程可以通过 forking 在 for
循环的每次迭代中实现一次:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
for (int i = 0; i < 4; i++) {
pid_t pid = fork();
if (pid == 0)
exit(0); // child process
// parent process
wait(NULL);
printf("At i = %d, process %d is terminated.\n", i, pid);
}
}
但是,您可能希望 parent 进程在 创建所有四个 children 之后等待 children ,因为您通常希望 children 在退出之前做一些事情并与另一个 children:
int main() {
// create the four children processes
for (int i = 0; i < 4; i++) {
pid_t pid = fork();
if (pid == 0) {
// child process
// ... do some stuff ...
exit(0);
}
}
// wait for the four children processes to finish
for (int i = 0; i < 4; i++) {
pid_t pid = wait(NULL);
printf("Process %d is terminated.\n", pid);
}
}
目标是尝试在一个循环中分叉 4 children,但我不确定如何正确地做到这一点。这是我到目前为止所拥有的。我试着把它画出来,我想我已经等不及要好好收割 child 了。我每次迭代都会创建 2 children。所以一共8children.
void main() {
int i = 0;
pid_t pid;
int status;
for(i = 0; i < 4; i++) {
pid = fork();
if(pid == 0) {
/* Child Process */
fork();
exit(0);
} else {
/* Parent Process */
wait(&status);
printf("At i = %d, process %d is terminated.\n", i, pid);
}
}
}
从同一个 parent 进程创建四个 children 进程可以通过 forking 在 for
循环的每次迭代中实现一次:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
for (int i = 0; i < 4; i++) {
pid_t pid = fork();
if (pid == 0)
exit(0); // child process
// parent process
wait(NULL);
printf("At i = %d, process %d is terminated.\n", i, pid);
}
}
但是,您可能希望 parent 进程在 创建所有四个 children 之后等待 children ,因为您通常希望 children 在退出之前做一些事情并与另一个 children:
int main() {
// create the four children processes
for (int i = 0; i < 4; i++) {
pid_t pid = fork();
if (pid == 0) {
// child process
// ... do some stuff ...
exit(0);
}
}
// wait for the four children processes to finish
for (int i = 0; i < 4; i++) {
pid_t pid = wait(NULL);
printf("Process %d is terminated.\n", pid);
}
}