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

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.

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

#include

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 ;

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值