zoukankan      html  css  js  c++  java
  • fork函数

    例1:

    #include <stdio.h>
    #include <unistd.h>
    
    int global_var = 1;
    
    int main(int argc, char* argv[])
    {
    	int var = 10;
    
    	if(fork() == 0)
    	{
    		printf("child process global_var = %d var = %d\n", ++global_var, ++var);
    	}
    	printf("pid = %d global_var = %d var = %d\n", getpid(), global_var, var);
    
    	return 0;
    }

    输出:

    pid = 12681 global_var = 1 var = 10
    child process global_var = 2 var = 11
    pid = 12682 global_var = 2 var = 11

    例2:

    #include <stdio.h>
    #include <unistd.h>
    
    int global_var = 1;
    
    int main(int argc, char* argv[])
    {
    	int var = 10;
    
    	if(fork() == 0)
    	{
    		printf("child process global_var = %d var = %d\n", ++global_var, ++var);
    	} else {
    		printf("pid = %d global_var = %d var = %d\n", getpid(), global_var, var);
    	}
    
    	return 0;
    }
    


    输出:

    pid = 12870 global_var = 1 var = 10
    child process global_var = 2 var = 11


     

    例3:

    #include <stdio.h>
    #include <unistd.h> 
    
    int global_var = 1; 
    
    int main(int argc, char* argv[])
    {
        int var = 10; 
    
        if(fork() == 0)
        {
            printf("child process global_var = %d var = %d\n", ++global_var, ++var);
            exit(0);
            //return 0;
        }
        printf("pid = %d global_var = %d var = %d\n", getpid(), global_var, var); 
    
        return 0;
    }
    

    输出:

    pid = 12920 global_var = 1 var = 10
    child process global_var = 2 var = 11

  • 相关阅读:
    恭介的法则
    229. Majority Element II
    169. Majority Element
    233. Number of Digit One
    172. Factorial Trailing Zeroes
    852. Peak Index in a Mountain Array
    162. Find Peak Element
    34. Find First and Last Position of Element in Sorted Array
    81. Search in Rotated Sorted Array II
    33. Search in Rotated Sorted Array
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2711046.html
Copyright © 2011-2022 走看看