1. 程式人生 > >【APUE | 08】程序控制

【APUE | 08】程序控制

函式fork

#include "apue.h"

int glob = 6;
char buf[] = "a write to stdout\n";
int main(void)
{
    int var;
    int pid;
    var = 88;
    if (write(STDOUT_FILENO, buf, sizeof(buf) - 1) != sizeof(buf) - 1)
    {
        err_sys("write error!\n");
    }
    printf("before fork!\n");
    if ((pid = fork())<0)
    {
        err_sys("fork error!\n");
    }
    else if (pid == 0) // this is child process for pid == 0 
    {
        glob++;
        var++;
    }
    else  //this is parent process
    {
        sleep(2); //wait for child finishing
    }
    printf("pid= %d,glob= %d,var= %d\n", getpid(), glob, var);
    exit(0);
}