用于Linux中IPC的shmget [英] shmget for IPC in linux

查看:217
本文介绍了用于Linux中IPC的shmget的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的是Linux操作系统的新手.有人可以说如何在linux上完成这项工作.我不是在问C代码.很难理解.谢谢
1.第一个程序使用shmget()创建一个共享内存区域,并将其映射到其地址空间.然后,它将"Hello"写入该共享内存区域.然后,它等待直到共享存储区中的第一个字节变为*.
2.第二个程序应在第一个程序之后启动.它将第一个程序创建的共享存储区映射到其地址空间,并读取字符串并将其打印到终端.然后,它将共享内存区域的第一个字节更改为*.

I'm really new to linux OS. Can someone say how to do this work with linux. I'm not asking the C code. It's hard to understand it. Thank you
1. First program creates a shared memory area using shmget() and maps it to its address space. Then it writes "Hello" in to that shared memory area. Then it waits until the first byte in the shared memory area becomes *.
2. The second program should be started after the first one. It maps the shared memory area created by the first program into its address space and reads the string and prints it to the terminal. Then it changes the first byte of the shared memory area to *.

推荐答案

我认为这就是您想要的.

I think this is what you're looking for.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>

#define SHSIZE 100

int main(){

    int shmid;
    char *shm;

    shmid = shmget(9876, SHSIZE, IPC_CREAT | 0660);
    shm = shmat(shmid, NULL, 0);
    memcpy(shm, "Hello", 5);

    while(*shm != '*'){
    sleep(1);
    }

return 0;
}

和客户:

#include <stdio.h>
#include <sys/shm.h>

#define SHSIZE 100

int main(){
    int shmid;
    char *shm,*s;

    shmid = shmget(9876, SHSIZE, IPC_CREAT | 0660);
    shm = shmat(shmid, NULL, 0);

    for(s = shm; *s != 0; s++){
    printf("%c", *s);
    }
    printf("\n");

    *shm = '*';

return 0;
}

这篇关于用于Linux中IPC的shmget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆