APUE course source code
guowenxue
2 days ago 9c22371ef5059a2e46226ee90a0667ffad65b574
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
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  mmap_ipc.c
 *    Description:  This file is Memory Map(IPC) example program.
 *
 *        Version:  1.0.0(11/10/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "11/10/2025 01:02:05 PM"
 *
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <string.h>
 
int main(void)
{
    char *shm = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    if (shm == MAP_FAILED)
    {
        perror("mmap");
        exit(1);
    }
 
    pid_t pid = fork();
    if (pid == 0)
    {
        /* 子进程 */
        strcpy(shm, "Message from child process");
    }
    else
    {
        /* 父进程 */
        sleep(1);
        printf("Parent read: %s\n", shm);
    }
 
    munmap(shm, 4096);
    return 0;
}