Linux 编程之进程fork()详解及实例

Badia ·
更新时间:2024-09-20
· 885 次阅读

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 kitty\n"); 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 ; }

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

您可能感兴趣的文章:详解linux中fork、vfork、clone函数的区别Linux中fork()函数实例分析使用C语言的fork()函数在Linux中创建进程的实例讲解浅谈Linux环境下并发编程中C语言fork()函数的使用Linux中使用C语言的fork()函数创建子进程的实例教程C语言的fork函数在Linux中的进程操作及相关面试题讲解简单掌握Linux系统中fork()函数创建子进程的用法Linux下C语言的fork()子进程函数用法及相关问题解析Linux系统中C语言编程创建函数fork()执行解析Linux 中fork的执行的实例详解



程之 Linux fork

需要 登录 后方可回复, 如果你还没有账号请 注册新账号