我不完全确定何时使用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因为我有两个ma不仅一个而且我不知道为什么
答案 0 :(得分:2)
是。该过程创建一个孩子,然后创建另一个孩子,成为它的父母 您可以使用fork返回号来区分child和parent。来自fork:
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.