Linux进程通信之shared memory(共享内存)

先写一个ser_shm.c:

#include"myutili.h"

int main()
{
    int shm_key = Ftok("myshm",0xff);
    int shm_id = shmget(shm_key, 1024*1024, IPC_CREAT|IPC_EXCL|0755);
    if(shm_id == -1)
    {
        perror("shmget.");
        exit(1);
    }
    char *address = (char*)shmat(shm_id, NULL, 0);
    if((void*)address == (void*)-1)
    {
        perror("shmat.");
        shmctl(shm_id, IPC_RMID, 0);
        exit(1);
    }
    key_t sem_key = Ftok("mysem", 0xff);
    int sem_id = semget(sem_key, 2, IPC_CREAT|IPC_EXCL|0755);
    union semun info;
    info.val = 0;
    semctl(sem_id,0, SETALL, info);
    struct sembuf p ={0, -1, 0}, v = {1, 1,0};
    while(1)
    {
        printf("Ser: >");
        scanf("%s", address);
        semop(sem_id, &v, 1);
        semop(sem_id, &p, 1);
        printf("Cli: >%s\n ",address);
    }
    shmdt(address);
    shmctl(shm_id, IPC_RMID, 0);
    shmctl(sem_id, 0, IPC_RMID);
    return 0;
}

写一个cli_shm.c:

#include"myutili.h"

int main()
{
    int shm_key = Ftok("myshm",0xff);
    int shm_id = shmget(shm_key, 0, 0);
    if(shm_id == -1)
    {
        perror("shmget.");
        exit(1);
    }
    char *address = (char*)shmat(shm_id, NULL, 0);
    if((void*)address == (void*)-1)
    {
        perror("shmat.");
        exit(1);
    }
    key_t sem_key = Ftok("mysem",0xff);
    int sem_id = Semget(sem_key, 0, 0);
    struct sembuf p = {1, -1, 0}, v = {0, 1, 0};
    while(1)
    {
        semop(sem_id, &p, 1);
        printf("Ser: >%s\n",address);
        printf("Cli: >");
        scanf("%s", address);
        semop(sem_id, &v, 1);
    }
    shmdt(address);
    return 0;
}

运行的检验:

运行的结果

用共享内存加信号量的方式简单实现的一种客户端和服务器端的对象。

你可能感兴趣的:(Linux)