zoukankan      html  css  js  c++  java
  • fork-小实验

    实验一(fork原理)

    fork之前的代码是共同执行的

    注意,子进程持有的是上述存储空间的“副本”,这意味着父子进程间不共享这些存储空间。
    UNIX将复制父进程的地址空间内容给子进程,因此,子进程有了独立的地址空间。

    #include <unistd.h>
    #include <stdio.h>
    #include<sys/types.h>
    int main ()
    {
        pid_t pid;
        int count=0;
        
    	int i;
    	pid=fork();
        if (pid < 0)
            printf("error in fork!");
        else if (pid == 0) {
            printf("child process, process id is %d
    ",getpid());
            count++;   }
        else {
            printf("parent process, process id is %d
    ",getpid());
    		count++;     
    	}
    	printf("result: %d
    ",count);
        return 0; 
    	
    }
    
    
    
    //执行结果是:
    /*
    parent process, process id is 47085
    result: 1
    child process, process id is 47086
    result: 1
    */
    
    
    
    
    

    实验二:

    fork(复刻)之后父进程的号不变,子进程的号+1

    #include<stdlib.h> 
    #include<stdio.h> 
    #include<unistd.h> 
    #include<sys/types.h> 
    int main(){ 
    	pid_t pid; 
    	printf("the main_process_before_fork ID is %d
    ",getpid()); 
    	pid=fork(); 
    	if(pid == 0 ){ 
    		printf("the 子—process ID is %d
    ",getpid()); 
    		printf("hello,i am a child process. pid is %d
    ",pid); 
    	} else{ 
    		printf("the 父-process ID is %d
    ",getpid()); 
    		printf("Hello,I'm a parent process.pid is %d
    ",pid);
    	} 
    	exit(0); 
    }
    
    /*执行结果:
    
    
    the main_process_before_fork ID is 48547
    the 父-process ID is 48547
    Hello,I'm a parent process.pid is 48548
    the 子—process ID is 48548
    hello,i am a child process. pid is 0
    
    
    
    */
    
    
  • 相关阅读:
    Log4net快速搭建
    WebAPI中Area的使用
    (三)Redis for StackExchange.Redis
    (二)Redis for 阿里云公网连接
    Python+CGI,在Windows上快速部署Python到IIS
    腾讯云
    UIView添加事件
    Sublime Text Packages Control 安装
    乎乎测试
    常用第三方类库
  • 原文地址:https://www.cnblogs.com/shallow920/p/14090642.html
Copyright © 2011-2022 走看看