【APUE】fork函數

來源:互聯網
上載者:User

標籤:style   blog   color   資料   io   for   代碼   div   

#include <unisth.h>

pid_t fork(void)

fork函數被調用一次,返回兩次。子進程的傳回值是0,父進程的傳回值是子進程的進程id。

子進程和父進程繼續執行fork調用之後的指令,子進程是父進程的副本,子進程獲得父進程資料空間、堆和棧的副本。注意:這是子進程所擁有的副本,父子進程並不共用這些儲存空間部分。父子進程共用本文段

#include <stdio.h>#include <sys/types.h>#include <unistd.h>int glob=6;//全域變數,在堆中char buf[]="a write to stdout\n";int main(){    int var;//局部變數,棧中    pid_t pid;    var =88;    if(write(STDOUT_FILENO,buf,sizeof(buf)-1)!=sizeof(buf)-1)    {        perror("write error");    }    printf("before fork:\n");    if((pid=fork())<0)    {        perror("fork error");    }    else if(pid==0)    {        glob++;        var++;    }    else{        sleep(2);    }    printf("pid=%d,glob=%d,var=%d\n",getpid(),glob,var);    exit(0);}

輸出:

a write to stdout
before fork:
pid=4989,glob=7,var=89
pid=4988,glob=6,var=88

fork的兩種用法:

1.一個父進程希望複製自己,使父子進程同時執行不同的程式碼片段

2.一個進程要執行一個不同的程式,在這種情況下,子進程從fork返回後立即調用exec

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.