Linux fork程式的用法

ericohe發表於2020-11-12

程式碼

// fork.cpp

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <sys/wait.h>

void fork_wait()
{
    int status, ret;
    int pid;
    pid = fork ();
    if (pid == 0) 
    {
        // I am the child
        printf ("Child: Work completed!\n");
        printf ("Child: Bye now.\n");
        sleep(20);
        exit (0);
    }
    // I am the parent
    printf ("Parent: Waiting for Child to complete.\n");
    if ((ret = waitpid (pid, &status, 0)) == -1)
         printf ("parent:error\n");

}

int main (int argc, char **argv)
{
    int i = 0;
    long sum;

    printf ("Parent: Hello, World!\n");
    while(1)
    {
       fork_wait();
       i++ ;
       std::cout<<"i="<<i<<"\n";
       sleep(2);
    }
}

編譯

g++ fork.cpp -o fork

 

執行

 ./fork
Parent: Hello, World!
Parent: Waiting for Child to complete.
Child: Work completed!
Child: Bye now.
i=1
Parent: Waiting for Child to complete.
Child: Work completed!
Child: Bye now.
i=2
Parent: Waiting for Child to complete.
Child: Work completed!
Child: Bye now.

結果 

pgrep fork
20390
20391
root@7f4dc6e8ef5e:/opt/bin# pgrep fork
20390
20394
root@7f4dc6e8ef5e:/opt/bin# pgrep fork
20390
20396

 

相關文章