9-10 text 2

发布于:2022-12-19 ⋅ 阅读:(117) ⋅ 点赞:(0)

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    key_t key = ftok("./", 1);
    if (key < 0)
    {
        perror("ftok");
        return -1;
    }
    printf("key = %#x\n", key);

    //创建共享内存
    int shmid = shmget(key, 64, IPC_CREAT | 0664);
    if (shmid == -1)
    {
        perror("shmget");
        return -1;
    }
    printf("shmid = %d\n", shmid);
    //将共享内存映射到用户空间;
    void *arg = shmat(shmid, NULL, 0);
    if ((void *)-1 == arg)
    {
        perror("shmat");
        return -1;
    }
    printf("arg = %p\n",arg);

    
    int *pa = (int *)arg;
    *pa = 0;

    char *pb = (char *)(pa + 1);

    strcpy(pb,"123456");
    //打印
    while (1)
    {
        if (0 == *pa)
        {
            printf("%s\n", pb);
        }
        *pa = 1;
    }
    return 0;
}

*///

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include  <string.h>
int main()
{
    key_t key = ftok("./", 1);
    if (key < 0)
    {
        perror("ftok");
        return -1;
    }
    printf("key = %#x\n", key);

    //创建共享内存
    int shmid = shmget(key, 64, IPC_CREAT | 0664);
    if (shmid == -1)
    {
        perror("shmget");
        return -1;
    }
    //将共享内存映射到用户空间;
    void *arg = shmat(shmid, NULL, 0);
    int *pa = (int *)arg;

    char *pb = (char *)(pa + 1);
    char *start, *end, temp;

    //打印
    while (1)
    {
        start = pb;
        end = start + strlen(start) - 1;
        if (1 == *pa)
        {
            while (start < end)
            {
                temp = *start;
                *start = *end;
                *end = temp;
                start++;
                end--;
            }
        }
        *pa = 0;
    }

    return 0;
}


网站公告

今日签到

点亮在社区的每一天
去签到