Linux 编程之进程fork()详解及实例
Linuxfork()详解:
在开始之前,我们先来了解一些基本的概念:
1.程序,没有在运行的可执行文件
进程, 运行中的程序
2.进程调度的方法:
按时间片轮转
先来先服务
短时间优先
按优先级别
3.进程的状态:
就绪 ->> 运行 ->>等待
运行->>就绪//时间片完了
等待->>就绪//等待的条件完成了
查看当前系统进程的状态psauxf
status:
D Uninterruptiblesleep(usuallyIO)
R Runningorrunnable(onrunqueue)
S Interruptiblesleep(waitingforaneventtocomplete)
T Stopped,eitherbyajobcontrolsignalorbecauseitisbeingtraced.
W paging(notvalidsincethe2.6.xxkernel)
X dead(shouldneverbeseen)
Z Defunct("zombie")process,terminatedbutnotreapedbyitsparent.
< high-priority(notnicetootherusers)
N low-priority(nicetootherusers)
L haspageslockedintomemory(forreal-timeandcustomIO)
s isasessionleader
l ismulti-threaded(usingCLONE_THREAD,likeNPTLpthreadsdo)
+ isintheforegroundprocessgroup
4.父进程/子进程,让一个程序运行起来的进程就叫父进程,被调用的进程叫子进程
5.getpid//获取当前进程的进程号
getppid//获取当前进程的父进程号
6.fork//创建一个子进程,创建出来的子进程是父进程的一个副本, 除了进程号,父进程号不同。
子进程从fork()后开始运行,它得到的fork返回值为0
父进程得到的返回值为子进程的进程号
返回值为-1时,创建失败
来看一个程序:
#include#include intmain(void) { pid_tpid; //printf("helloworld\n"); //从fork开始就已经产生子进程 pid=fork();//就已经产生新的4G空间,复制空间 //创建出来的子进程是父进程的一个副本,除了进程号,父进程号和子进程号不同 //printf("hellokitty\n"); if(pid==0) { //子进程运行区 printf("childcurpid:%dparentpid:%d\n",getpid(),getppid()); return0; } //父进程运行区 printf("parentcurpid:%dparentpid:%d\n",getpid(),getppid()); return0; }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!