gpt4 book ai didi

c - shmat() 为不同的程序返回不同的地址,所有程序都具有相同的共享内存

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:46 27 4
gpt4 key购买 nike

<分区>

在共享内存中,据我了解,使用 shmat() 调用在附加到它的两个进程之间共享相同的逻辑地址。那么为什么我为下面的程序获得不同的内存地址(在输出中),即使它们共享相同的地址。

//Shm_Server.C

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXSIZE 27

void die(char *s)
{
perror(s);
exit(1);
}

int main()
{
char c;
int shmid;
key_t key = 5678;
char *shm_addr, *s;

if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)
die("shmget");

if ((shm_addr = (char *)shmat(shmid, NULL, 0)) == (char *) -1)
die("shmat");
printf("\nServer shm_addr = %x\n",shm_addr);

s = shm_addr;
for (c = 'a'; c <= 'z'; c++)
*s++ = c;

while (*shm_addr != '*')
sleep(1);

if((shmctl(shmid, IPC_RMID, 0)) < 0)
die("shmctl");
exit(0);
}

//Shm_Client.C

#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXSIZE 27

void die(char *s)
{
perror(s);
exit(1);
}

int main()
{
int shmid;
key_t key = 5678;
char *shm_addr, *s;

if ((shmid = shmget(key, 0, 0666)) < 0)
die("shmget");

if ((shm_addr = (char *) shmat(shmid, NULL, 0)) == (char *) -1)
die("shmat");
printf("\nClient shm_addr = %x\n", shm_addr);

//reading what the server put in shared memory
for (s = shm_addr; *s != '\0'; s++)
putchar(*s);
putchar('\n');

//Writing in shared memory
*shm_addr = '*';
exit(0);
}

Output:

[xyz@xyz:Shm_ex] $ ./Shm_Server &
[1] 19489
[xyz@xyz:Shm_ex] $
Server shm_addr = d92b5000
./Shm_Client

Client shm_addr = eb3c4000
abcdefghijklmnopqrstuvwxyz
[xyz@xyz:Shm_ex] $

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com