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
    
    
    
    */
    
    
  • 相关阅读:
    iOS 设计模式-委托模式
    python中时间操作总结
    list、dict、tuple的一些小操作总结
    DataFrame的构建及一些操作
    python连接mysql、oracle小例子
    sqlalchemy 映射的小例子
    crontab定时任务以及其中中文乱码问题
    vs2008试用版的评估期已经结束解决办法
    MongoDB 常用shell命令汇总
    把py文件打成exe
  • 原文地址:https://www.cnblogs.com/shallow920/p/14090642.html
Copyright © 2011-2022 走看看