【发布时间】:2015-07-23 20:30:13
【问题描述】:
我在运行代码时遇到问题。我的 shmat 失败并打印权限被拒绝。我在谷歌上搜索了如何解决它,但我不能。我的代码如下:
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#define ERROR -1
int main ( int argc, char *argv[] ) {
int shmid,key=50;
int *val;
int *x;
int rw = -1;
// 0 for write and 1 for read
shmid = shmget ( key, sizeof( int ), IPC_CREAT );
if ( shmid == -1 ) {
perror ( "Error in shmget\n" );
return ( ERROR );
}
val = ( int * ) shmat ( shmid, NULL, 0 );
if ( val == -1 ) {
perror ( "Error in shmat\n" );
return ( ERROR );
}
scanf ( "%d", &rw);
while ( rw >= 0 ) {
if ( rw == 0 ) {
//write in the shared memory
x = ( int * ) malloc ( sizeof ( int ) );
if ( x == NULL ) {
perror ( "Error in malloc" );
return ( ERROR );
}
scanf ( "%d", x );
val = x;
}
else {
// read from the shared memory
if ( rw == 1 ) {
printf ( "%d\n", *val );
}
}
scanf ( "%d", &rw );
}
return ( 0 );
}
在这段代码中,我想测试共享内存。当我给 rw = 1 时,我在共享内存中写入一个整数,否则我读取共享内存的值,然后打印该值。我找不到问题出在哪里......
【问题讨论】:
-
1) 在调用 scanf() 和函数族时,始终检查返回值(而不是参数)以确保操作成功。 2) 在 C 中,不要从 malloc() 和函数族中转换返回值。
-
在运行发布的代码时,用户没有指示唯一有效的输入值是 1 和 0。用户看到的只是一个提示。此外,如果用户只输入换行符,则发布的代码将尝试处理内存中“*x”变量中发生的任何垃圾。
-
每次用户输入 0 时,都会执行另一个 malloc,覆盖之前的 malloc 指针(这会导致内存泄漏)每次执行 malloc 时,除第一次外,都需要将先前分配的内存指针传递给 free()。注意:如果 'x' 被初始化为 NULL,那么总是可以将 'x' 传递给 free()
-
'val' 指向共享内存。用“x”中的内容覆盖该指针会导致内存泄漏。在返回之前需要分离/销毁共享内存。需要在 return 语句之前执行对 free(x) 的最终调用。
-
编译时,所有的警告都需要开启,然后你会看到(至少)两个警告。 1) 未使用的参数 'argc' 2) 未使用的参数 'argv[]'
标签: c memory shared-memory