C++ fork函数理解
生活随笔
收集整理的這篇文章主要介紹了
C++ fork函数理解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++的fork函數用來“復制”一份主程序,即創(chuàng)建主進程的子進程。調用fork的同時,我的理解是,已經在內存中創(chuàng)建了“副本”進程,同時返回pid,所以在返回值之前,已經是主進程和子進程同時在運行了(如果fork成功的話),這樣,在程序的運行過程中,一次fork返回了兩次值,在父進程中,fork返回新創(chuàng)建子進程的進程ID,在子進程中,fork返回0,這時候就能夠同時跑兩個進程了。
實列如下:
運行結果:
before fork after fork fork success,this is father process,son process id is 11054 this is father process,i=2 after fork fork success,this is son process this is son process,i=1 this is son process,i=2 this is father process,i=4 this is son process,i=3 this is son process,i=4 this is father process,i=6 this is son process,i=5 this is son process,i=6 this is father process,i=8 this is son process,i=7 this is son process,i=8 this is father process,i=10 this is son process,i=9 this is son process,i=10在程序中,我們可以看到,fork函數調用之后,輸出了兩個“after fork”,也就是程序已經存在兩個進程在跑;有一個變量i,在fork之前定義,然后在fork之后的運行過程中,子進程和主進程中的i值互不影響,兩個進程同時在執(zhí)行,可以驗證fork是將主進程的資源全部拷貝了一份給子進程,兩個進程的資源是獨立的,互不影響。
總結
以上是生活随笔為你收集整理的C++ fork函数理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言是非结构化程序语言_1、C语言是一
- 下一篇: 计算机应用基础试题及答案电大百度云,电大