zoukankan      html  css  js  c++  java
  • 简单fork循环分析

    简单fork循环分析

    分析下列代码

    	/**********************************************************************
    
    		> File Name: t_fork.c
    
    		> Author: 0nism
    
    		> Email: fd98shadow@sina.com
    
    		> Created Time: Sun 14 Oct 2018 02:41:39 PM CST
    
    	***********************************************************************/
    
    	#include <unistd.h>
    	#include <stdio.h>
    	#include <stdlib.h>
    
    	static int idata = 111;         //  Allocated in data segment
    
    	int main(int argc, char **argv)
    	{
    		int istack = 222;           //  Allocated in stack segment
    		pid_t childPid;
    
    		int i = 0;
    
    		for ( i=0; i<2; i++)
    		{   
    			switch (childPid = fork())
    			{   
    				case -1: 
    							printf("err: fork
    ");
    							return 0;
    
    				case 0:
    							printf("child: ok
    ");
    							break;
    
    				default:
    							printf("parent: ok
    ");
    							break;
    			}   
    
    		} 
    		
    		exit(EXIT_SUCCESS);
    	}	
    

    在bash中输出为:

    	MISlike@16:43:~/process $ ./t_fork              
    	parent: ok
    	parent: ok
    	MISlike@16:43:~/process $ child: ok
    	child: ok
    	parent: ok
    	child: ok
    

    父进程1输出2次ok,循环2次创建子进程child0,child1。child0在fork时i=0,故也输出2次ok,i=1时,child0创建子进程child00。child1在fork时故输出1次ok。child00创建时i=1,输出1次ok。共计六次。循环次数为3时,也应该用类似手段分析。

    分析
    分析

  • 相关阅读:
    笔记2-斐波那契数列
    笔记1-排序
    C++ 顶层const和底层const ?
    C++指针常量与常量指针的区别?
    C++指针和引用的区别?
    函数指针, 指针函数?
    手机横竖屏问题
    Swift
    Swift 渐变色
    Swift guard 关键字
  • 原文地址:https://www.cnblogs.com/0nism/p/9792446.html
Copyright © 2011-2022 走看看