Linux fork()详解:
在开始之前,我们先来了解一些基本的概念:
1. 程序, 没有在运行的可执行文件  
   进程,  运行中的程序    
2. 进程调度的方法:  
    按时间片轮转   
    先来先服务  
    短时间优先  
    按优先级别    
3. 进程的状态:       
        就绪   ->>   运行  ->> 等待  
        运行 ->> 就绪 //时间片完了  
        等待 ->> 就绪 //等待的条件完成了    
查看当前系统进程的状态 ps auxf  
status:  
D    Uninterruptible sleep (usually IO)  
R    Running or runnable (on run queue)  
S    Interruptible sleep (waiting for an event to complete)  
T    Stopped, either by a job control signal or because it is being traced.  
W    paging (not valid since the 2.6.xx kernel)  
X    dead (should never be seen)  
Z    Defunct ("zombie") process, terminated but not reaped by its parent.  
<    high-priority (not nice to other users)  
N    low-priority (nice to other users)  
L    has pages locked into memory (for real-time and custom IO)  
s    is a session leader  
l    is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)  
+    is in the foreground process group    
4. 父进程/子进程 , 让一个程序运行起来的进程就叫父进程, 被调用的进程叫子进程    
5. getpid //获取当前进程的进程号  
   getppid //获取当前进程的父进程号    
6. fork //创建一个子进程,创建出来的子进程是父进程的一个副本, 除了进程号,父进程号不同。  
    子进程从fork()后开始运行, 它得到的fork返回值为0  
    父进程得到的返回值为子进程的进程号  
    返回值为-1时, 创建失败
来看一个程序:
#include <stdio.h> 
#include <unistd.h> 
int main(void) 
{ 
  pid_t pid ;  
  //printf("hello world n"); 
  //从fork开始就已经产生子进程 
  pid = fork();  //就已经产生新的4G空间,复制空间 
  //创建出来的子进程是父进程的一个副本,除了进程号,父进程号和子进程号不同 
  //printf("hello kittyn"); 
  if(pid == 0)   
  { 
    //子进程运行区 
    printf("child curpid:%d parentpid:%d n" , getpid() , getppid()); 
    return 0 ;  
  } 
  //父进程运行区 
  printf("parent curpid:%d parentpid:%d n" , getpid() , getppid()); 
  return 0 ;  
} 
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!