APUE course source code
guowenxue
yesterday 7b55c92f8d1401a93c8fd8e342da271dce742000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  fork.c
 *    Description:  This file is fork() example program.
 *
 *        Version:  1.0.0(10/27/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "10/27/2025 10:39:48 AM"
 *
 ********************************************************************************/
 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
 
int main(void)
{
    int var = 10;
    pid_t pid;
 
    printf("parent process pid[%d] running...\n", getpid() );
    printf("before fork: var=%d, addr=%p\n", var, &var);
    printf("\n");
 
    pid = fork();
 
    if (pid < 0)
    {
        printf("fork() create child process failure: %s\n", strerror(errno));
        exit(1);
    }
    else if (pid == 0)
    {
        printf("child process pid[%d] running, parent pid is [%d]\n", getpid(), getppid());
        var = 20;  /* 子进程修改变量 */
        printf("child process space: var=%d, addr=%p\n", var, &var);
    }
    else if( pid > 0 )
    {
        sleep(1); /* 父进程等待片刻,让子进程先执行 */
        printf("parent process pid[%d] running, child pid is [%d]\n", getpid(), pid);
        printf("parent process space: var=%d, addr=%p\n", var, &var);
    }
 
    printf("process pid[%d] exit\n\n", getpid());
 
    return 0;
}