gpt4 book ai didi

c - 使用 ipcrm 删除共享内存 linux

转载 作者:太空宇宙 更新时间:2023-11-04 10:43:33 24 4
gpt4 key购买 nike

我正在使用共享内存在 C 上编写一个简单的应用程序,但我无法再运行它,因为它说:

shmat:无法分配内存

我正在使用 this脚本来释放我的内存,但似乎不起作用。

这是我的流程截图:

enter image description here

这是应用程序代码:

/* Shared Memory IPC creates a mamory space and send contendt to it while the other process can read from it.
Our implementation works like this:
1. First run the application by passing as a argument the value you want to send to the shared memory. Example: ./ipc_sharedmem.o 4
2. Run the appliation again to read from the shared memory (which is a new process, of course) wihout sending any arguments. Exmaple: ./ipc_sharedmem.o
*/

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

#define SHM_SIZE 1024 /* make it a 1K shared memory segment */

int main(int argc, char *argv[])
{
key_t key;
int shared_mem_mid;
char *data;

struct timeval t1, t2, t3, t4;

if (argc > 2) {
fprintf(stderr, "usage: shmdemo [data_to_write]\n");
exit(1);
}

/* make the key: */
if ((key = ftok("mach.c", 'R')) == -1) {
perror("ftok");
exit(1);
}

/* connect to (and possibly create) the segment: */
if ((shared_mem_mid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
perror("shmget");
exit(1);
}

/* attach to the segment to get a pointer to it: */
gettimeofday(&t1, NULL);
data = (char *) shmat(shared_mem_mid, (void *)0, 0);
gettimeofday(&t2, NULL);
if (data == (char *)(-1)) {
perror("shmat");
exit(1);
}

printf("Time to read the message from sharem memory: %g \n", (t2.tv_sec + t2.tv_usec/1000000.0)-(t1.tv_sec + t1.tv_usec/1000000.0));

/* read or modify the segment, based on the command line: */
if (argc == 2) {
printf("writing to segment: \"%s\"\n", argv[1]);
gettimeofday(&t3, NULL);
strncpy(data, argv[1], SHM_SIZE);
gettimeofday(&t4, NULL);
printf("Time to send data to shared memory: %g \n", (t4.tv_sec + t4.tv_usec/1000000.0)-(t3.tv_sec + t3.tv_usec/1000000.0));
} else{

printf("segment contains: \"%s\"\n", data);
}
/* detach from the segment: */
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}

return 0;
}

有什么想法吗?

最佳答案

您的共享内存段被标记为已销毁,但仍附加有进程。

根据 source codenattach 列为 2,status 为“dest”,这意味着共享内存段有 2 个附件,一旦最后一个附加进程与段。

您需要让附加到段的进程调用 shmdt() 以从共享内存段分离,或者您需要终止这些进程。一旦你这样做,这些片段将被销毁。

关于c - 使用 ipcrm 删除共享内存 linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34040537/

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