zoukankan      html  css  js  c++  java
  • fork()函数 图解

    code

    #include<stdio.h>
    #include <getopt.h>
    #include<iostream>
    #include<string>
    #include<stdlib.h>
    using namespace std;
    
    int main(int argc, char* argv[]) {
        pid_t pid=0;
        int clients=2;
        printf("parent %d
    ",getpid());
    
        for(int i=0;i<clients;i++)
        {
            //在fork函数执行完毕后,如果创建新进程成功,则出现两个进程,一个是子进程,一个是父进程。
            //在子进程中,fork函数返回0,在父进程中,fork返回新创建子进程的进程ID。
            //我们可以通过fork返回的值来判断当前进程是子进程还是父进程。
            pid=fork();
    
            if( pid < (pid_t) 0)
            {
                printf("something wrong!");
            }
            if(pid <= (pid_t) 0)
            {
                /* child process or error*/
                //sleep(1); /* make childs faster */
            }
            if(pid == (pid_t) 0)
            {
                printf("index%d child : ppid:%4d pid:%4d fpid:%4d
    ",i,getppid(),getpid(),pid);
            }
            else
            {
                printf("index%d parent : ppid:%4d pid:%4d fpid:%4d
    ",i,getppid(),getpid(),pid);
            }
        }
        return 0;
    }

    输出

    parent 88993
    
    index0 parent : ppid:88994 pid:88993 fpid:88996
    index0 child : ppid:88993 pid:88996 fpid:   0
    
    index1 parent : ppid:88994 pid:88993 fpid:88997
    index1 child : ppid:88993 pid:88997 fpid:   0
    index1 parent : ppid:88993 pid:88996 fpid:88998
    index1 child : ppid:88996 pid:88998 fpid:   0
    
    Program ended with exit code: 0

    根据输出结果,我们画出下面这个结构图

    可以看到,由于我是使用Xcode运行的代码,Xcode的pid是88994

    以上代码运行后的进程pid是88993

    两次循环以后,88993 fork 出了88996,88997,88998三个子进程,算上自身,一共有四个进程。

    i=0时,88993创建了一个子进程88996,此时这两个进程的程序的i=1,也就是说,此时两个进程开始执行的位置是一样的,是从88993执行完第一次循环后的那个 位置开始执行。

    参考:

    https://www.cnblogs.com/love-jelly-pig/p/8471206.html

  • 相关阅读:
    设置github使用的SSH key
    Github的两种协议SSH和HTTPS
    OSChina 周一乱弹 —— 为什么人类和人工智能定要一战
    OSChina 周一乱弹 —— 为什么人类和人工智能定要一战
    APP路由还能这样玩
    APP路由还能这样玩
    APP路由还能这样玩
    APP路由还能这样玩
    掘金技术社区沸点指南(试行版)
    掘金技术社区沸点指南(试行版)
  • 原文地址:https://www.cnblogs.com/sea-stream/p/11234950.html
Copyright © 2011-2022 走看看