fork进程的一些处理,

开发者在线 Builder.com.cn 更新时间:2008-03-27作者:木木 来源:CSDN

本文关键词: 处理 进程 fork 开源

exit(0) //正常退出当前进程
fork() //之后的语句,子进程和父进程同时运行。但是在子进程中fork返回0,在父进程中fork返回大于1的进程ID。也就是说,你定义的I在父进程和子进程中有不同的值。

if(fork()==0)


通过一个小例子分析fork的工作原理。

#include <stdio.h>
#include 
<unistd.h>


int main(){

    
char father[]="father";
    
char child[]="child";
    
int nPid,nFatherPid;
     
//asigned and then compared.
    if((nPid=5)==5)printf("success %d! ",(nPid=3));

    nFatherPid
=getpid();
    printf(
"father getpid()=%d ",getpid());

    
if((nPid=fork())==0){// child process,in child process fork() return 0
   
        printf(
"child getpid()= %d nPid=%d ",getpid(),nPid);

    }

    
if(nPid==nFatherPid){
        printf(
"father getpid()=%d, nFatherPid=%d  ",getpid(),nFatherPid);
    }

    
//father and child are also running.
     printf("father or child ,getpid()=%d nPid=%d ",getpid(),nPid);

    
//child stoped.
     if(nPid==0)exit(0);

     printf(
"father nPid=%d  ",nPid);
     printf(
"getpid()=%d ",getpid());
    
return 1;

 

}
 

用户评论

  • 用户名
  • 评论内容