【IPC通信】System V共享内存操作

System V共享内存的简单使用:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

struct SHM_CONF
{
    int  pid;
    int  run_status;
    char status_desc[64];
};

/*创建共享内存,子进程写入消息,父进程读出并删除共享内存*/
/*共享内存名字由参数提供*/
int main(int argc, char *argv[])
{
    key_t shm_key;
    int shm_id;
    char *ptr;
    int rc;
    int pid;

    if(argc < 2)
    {
        printf("Usage: shmoper <name>\n");
        exit(1);
    }

    /*申请共享内存*/
    shm_key = ftok(argv[1], 1);
    if(-1 == shm_key)
    {
        perror("Generate IPC key error.");
        exit(1);
    }
    shm_id = shmget(shm_key, sizeof(struct SHM_CONF), IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
    if(-1 == shm_id)
    {
        perror("Get shared memory segment error.");
        exit(1);
    }

    /*将共享内存附接到本进程空间*/
    ptr = shmat(shm_id, NULL, 0);
    if((char *)-1 == ptr)
    {
        perror("Shared memory attach operation error.");
        exit(1);
    }

    /*创建子进程向共享内存写入数据*/
    pid = fork();
    if(0 == pid)
    {
        struct SHM_CONF *pshm = (struct SHM_CONF *)ptr;
        pshm->pid = (int)getpid();
        pshm->run_status = 0;
        strcpy(pshm->status_desc, "I'm OK.");
        shmdt(ptr); //shmat的逆过程,非必须操作,进程结束后会自动断接
        exit(1);
    }
    else if(pid > 0)
    {
        wait(NULL); // 等待子进程写完
        struct SHM_CONF *pshm = (struct SHM_CONF *)ptr;
        printf("child pid is : %d\n", pshm->pid);
        printf("child status : %s\n", pshm->status_desc);
    }

    /*删除共享内存*/
    shmdt(ptr);//shmat的逆过程,非必须操作,进程结束后会自动断接
    rc = shmctl(shm_id, IPC_RMID, NULL);
    if(-1 == rc)
    {
        perror("Shared memory delete operation error.");
        exit(1);
    }

    return 0;
}

2011-11-22 任洪彩  [email protected]

转载请注明出处。

你可能感兴趣的:(共享内存,IPC通信,SystemV)