Linux系统编程-----进程fork()
生活随笔
收集整理的這篇文章主要介紹了
Linux系统编程-----进程fork()
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在開始之前,我們先來了解一些基本的概念:
1. 程序, 沒有在運(yùn)行的可執(zhí)行文件
進(jìn)程, 運(yùn)行中的程序
2. 進(jìn)程調(diào)度的方法:
按時間片輪轉(zhuǎn)
先來先服務(wù)
短時間優(yōu)先
按優(yōu)先級別
3. 進(jìn)程的狀態(tài):
就緒 ->> 運(yùn)行 ->> 等待
運(yùn)行 ->> 就緒 //時間片完了
等待 ->> 就緒 //等待的條件完成了
查看當(dāng)前系統(tǒng)進(jìn)程的狀態(tài) 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. 父進(jìn)程/子進(jìn)程 , 讓一個程序運(yùn)行起來的進(jìn)程就叫父進(jìn)程, 被調(diào)用的進(jìn)程叫子進(jìn)程
5. getpid //獲取當(dāng)前進(jìn)程的進(jìn)程號
getppid //獲取當(dāng)前進(jìn)程的父進(jìn)程號
6. fork //創(chuàng)建一個子進(jìn)程,創(chuàng)建出來的子進(jìn)程是父進(jìn)程的一個副本,
除了進(jìn)程號,父進(jìn)程號不同。
子進(jìn)程從fork()后開始運(yùn)行, 它得到的fork返回值為0
父進(jìn)程得到的返回值為子進(jìn)程的進(jìn)程號
返回值為-1時, 創(chuàng)建失敗
來看一個程序:
#include <stdio.h>
#include <unistd.h>
int main(void)
{
pid_t pid ;
//printf("hello world \n");
//從fork開始就已經(jīng)產(chǎn)生子進(jìn)程
pid = fork(); //就已經(jīng)產(chǎn)生新的4G空間,復(fù)制空間
//創(chuàng)建出來的子進(jìn)程是父進(jìn)程的一個副本,除了進(jìn)程號,父進(jìn)程號和子進(jìn)程號不同
//printf("hello kitty\n");
if(pid == 0)
{
//子進(jìn)程運(yùn)行區(qū)
printf("child curpid:%d parentpid:%d \n" , getpid() , getppid());
return 0 ;
}
//父進(jìn)程運(yùn)行區(qū)
printf("parent curpid:%d parentpid:%d \n" , getpid() , getppid());
return 0 ;
}
總結(jié)
以上是生活随笔為你收集整理的Linux系统编程-----进程fork()的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ArcGIS工具 - 导出数据库结构
- 下一篇: Linux中的ln