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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  shm_read.c
 *    Description:  This file is Shared Memory(read) example program
 *
 *        Version:  1.0.0(11/10/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "11/10/2025 11:08:24 AM"
 *
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
 
#define FTOK_PATH           "/dev/zero"
#define FTOK_PROJID         0x22
 
typedef struct student_s
{
    char            name[64];
    int             age;
} student_t;
 
int main(int argc, char **argv)
{
    student_t     *student;
    key_t          key;
    int            shmid;
    int            i;
 
    if( (key=ftok(FTOK_PATH, FTOK_PROJID)) < 0 )
    {
        printf("ftok() get IPC token failure: %s\n", strerror(errno));
        return -1;
    }
 
    shmid = shmget(key, sizeof(*student), IPC_CREAT|0666);
    if( shmid < 0)
    {
        printf("shmget() create shared memroy failure: %s\n", strerror(errno));
        return -2;
    }
 
    student = shmat(shmid, NULL, 0);
    if( (void *)-1  == student )
    {
        printf("shmat() alloc shared memroy failure: %s\n", strerror(errno));
        return -2;
    }
 
    for(i=0; i<4; i++)
    {
        printf("Student '%s' age [%d]\n", student->name, student->age);
        sleep(1);
    }
 
    shmdt(student);
    shmctl(shmid, IPC_RMID, NULL);
 
    return 0;
}