14_02__shmWriteZ

ZC: Unix网络编程第2版 第2卷 第14章

 

1、

#include <iostream>
using namespace std;

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SVSHM_MODE (SHM_R | SHM_W | SHM_R >> 3 | SHM_R >> 6)

int main(int argc, char** argv)
{
    cout << "*** shmwrite *** Z ***" << endl;

    int i, id;
    struct shmid_ds buff;
    unsigned char *ptr;

    if (argc != 2)
    {
        printf("usage : shmread <pathname>\n");
        exit(0);
    }

    key_t key = ftok(argv[1], 0);
    if (key == -1)
    {
        printf("ftok return -1, errno : %d\n", errno);
        exit(0);
    }
    id = shmget(key, 0, SVSHM_MODE);
    if (id == -1)
    {
        // EACCES
        printf("shmget return -1, errno : %d\n", errno);
        exit(0);
    }
    ptr = (unsigned char*)shmat(id, NULL, 0);
    shmctl(id, IPC_STAT, &buff);
    printf("write --> buff.shm_segsz : 0x%08X, %d\n", buff.shm_segsz, buff.shm_segsz);

    for (i=0; i<(int)buff.shm_segsz; i++)
        *ptr++ = (i%256);

    exit(0);

    return 0;
}

 

2、

 

posted @ 2016-05-03 16:21  LinuxCode  阅读(199)  评论(0)    收藏  举报