C - 从子进程创建子进程



我不完全确定何时将fork((用于子进程进程 有子进程创建其他子进程,即使子进程是其他进程的父进程(状态为 0(?

#include <stdio.h>
int main()
{
printf("new proces");
if (fork() == 0) {
printf("child parent");
if (fork() == 0)
printf("child child");
}
printf("n");
}

我很困惑,因为我不确定当子进程调用 fork(( 时它是否会创建新进程? 因为在此代码中

#include<stdio.h>
int main(){
printf(" do ");
if(fork()!=0) printf("ma ");
if(fork()==0) printf("to n");
else printf("n");

}

我的结果就像在这段代码中有一个子父进程,它的状态为 0,我不知道为什么,因为它是第一个父进程的子进程

do ma 
do ma to
do to
do

不是这样的

do ma
do do to
to

子进程调用 fork 不返回 0 beause 我有两个 ma 不仅一个,我不知道为什么

是的。该过程创建一个子项,然后创建另一个子项,成为其父项。
您可以使用分叉返回编号来区分子项和父项。从叉子:

On success, the PID of the child process is returned in the parent, 
and 0 is returned in the child. On failure, -1 is returned in the parent, 
no child process is created, and errno is set appropriately.

你需要检查 fork(( 返回值。如果它返回 0,则表示此过程是子进程。如果它返回的值大于 0,则此进程是父进程,返回值是子进程 ID。 看看这个程序。我添加了usleep调用以使进程一个接一个地打印:

#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
int main(){
// lets create a family!
pid_t grandpa_pid = getpid();
pid_t child_pid;
if ((child_pid = fork()) == 0){
pid_t parent_pid = getpid();
pid_t child_child_pid;
if ((child_child_pid = fork()) == 0) {
usleep(200);
printf("I am child and I will write third. My pid is %d, %d is my parent and %d is my parents parent, so my grandpa.", getpid(), parent_pid, grandpa_pid);
} else {
usleep(100);
// parent_pid = getpid()
printf("I am parent and I will write second. My pid is %d, %d is my child and %d is my parent.", getpid(), child_child_pid, grandpa_pid);
}
} else {
// grandpa_pid == getpid()
printf("I am grandpa and I will write first. My pid is %d and %d is my child.", getpid(), child_pid);
}
printf("n");
}

这将产生以下输出:

I am grandpa and I will write first. My pid is 5 and 6 is my child.                                                                                                                
I am parent and I will write second. My pid is 6, 7 is my child and 5 is my parent.                                                                                                
I am child and I will write third. My pid is 7, 6 is my parent and 5 is my parents parent, so my grandpa.                                                                          

最新更新