我正在用C编写一个使用共享内存的简单应用程序,但我不能再运行它了,因为它写道:
shmat: Cannot allocate memory
我正在使用this脚本来释放我的内存,但似乎不起作用。
这是我的流程的屏幕截图:
这是应用程序代码:
/* 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;
}
有什么想法吗?
发布于 2015-12-02 19:25:28
您的共享内存段被标记为要销毁,但仍有附加到它们的进程。
对于每个source code,nattach
列是2,status
是"dest",这意味着共享内存段有2个附件,一旦最后一个附加的进程从该段分离,它们就被标记为销毁。
您需要将进程附加到调用shmdt()
的段,以便从共享内存段分离,或者需要杀死这些进程。一旦你这样做了,这些段就会被销毁。
发布于 2015-12-02 18:46:57
您是否尝试过(以root用户身份):
$ sync; echo 3 > /proc/sys/vm/drop_caches
不确定这是否会释放您的共享内存,但您可以尝试。
如果你想看一个例子,这里有一个要点:https://gist.github.com/hudsantos/7fec7d9c34cc472b7f98
https://stackoverflow.com/questions/34040537
复制相似问题