shmget 出错

标签:
shmgetit |
分类: Linux |
我写了一个程序如下
#include <stdio.h>;
#include <stdlib.h>;
#include <unistd.h>;
#include <sys/types.h>;
#include <sys/ipc.h>;
#include <sys/shm.h>;
#include <errno.h>;
extern int errno;
void main()
{
key_t key = 127;
int shmid;
char *shm_ptr;
if ( shmid = shmget( key, 100, 0666 | IPC_CREAT
|IPC_EXCL ) == -1 )
{
perror( "shmget error:
");
exit( 1 );
}
printf( " shmid is %d \n", shmid );
shm_ptr = ( char * )shmat( shmid, (char * )0, 0
);
if ( shm_ptr == ( char *) -1 )
{
printf("errno is %d :\n",
errno );
perror( "shmat
error:");
exit( 1 );
}
shm_ptr[0]='a';
shm_ptr[1]='b';
shm_ptr[2]='c';
getchar();
shmdt( shm_ptr );
shmctl( shmid, IPC_RMID, 0);
getchar();
printf(
"shm_ptr[0] is %c \n",
shm_ptr[ 0 ] );
}
在solaris 8上运行结果总是
shmid is 0
errno is 22 :
shmat error:: Invalid argument
我把key换成其他值也一样。
不知道我那里写错了,请诸位指教。
谢谢
http://www.lslnet.com/images/icon_new.gif出错" TITLE="shmget出错" />shmget 出错
呵呵真是有意思!原来竟是这个。。。
好象这个shimid = .. == ..是种很标准的写法,所有编译器都会支持吧?最多有个warring
#include <stdio.h>;
#include <stdlib.h>;
#include <unistd.h>;
#include <sys/types.h>;
#include <sys/ipc.h>;
#include <sys/shm.h>;
#include <errno.h>;
extern int errno;
void main()
{
}
在solaris 8上运行结果总是
shmid is 0
errno is 22 :
shmat error:: Invalid argument
我把key换成其他值也一样。
不知道我那里写错了,请诸位指教。
谢谢
http://www.lslnet.com/images/icon_new.gif出错" TITLE="shmget [code] if ( shmid = shmget( key, 100, 0666 | IPC_CREAT |IPC_EXCL ) == -1 ) [/code] -------------->; [code] if ( (shmid = shmget( key, 100, 0666 | IPC_CREAT |IPC_EXCL )) == -1 ) [/code] shmctl( shmid, IPC_RMID, 0); getchar(); printf( "shm_ptr[0] is %c \n", shm_ptr[ 0 ] ); 删除以后再读??好象会coredump。 |
http://www.lslnet.com/images/icon_new.gif出错" TITLE="shmget 现在主要问题是shmat不成功。 |
http://www.lslnet.com/images/icon_new.gif出错" TITLE="shmget IPC_CREAT |IPC_EXCL 这个设置导致排他型的创建。如果shmget失败的话,请去掉IPC_EXCL 如果在shmat失败的话,一般因为权限不足,或者引用的IPC对象的键值(如有时system V)或Posix IPC 名字(对于Posix而言)不正确所导致的。 如果如上确保正确的话,请检查errno和strerror(errno)。 |
http://www.lslnet.com/images/icon_new.gif出错" TITLE="shmget 多谢回复。虽然有点打击大家,我最后查处的结果是一个简单错误,如下: if ( shmid = shmget( key, 100, 0666 | IPC_CREAT |IPC_EXCL ) == -1 ) 从我的结果也可以看出,无论如何执行shmid都为0,因为上句编译器是如此解析的:shmid = ( shmget( key, 100, 0666 | IPC_CREAT |IPC_EXCL ) == -1) ),显然shmid是永远为0的。 另外,当shmget出错时,返回值绝对是-1,所以与flag是没有关系的。 PS : 昨天郁闷了半天,以为自己连这么简单的东西都写不出来了。 呵呵。不过有的编译器这个程序是没错的。 |
http://www.lslnet.com/images/icon_new.gif出错" TITLE="shmget
呵呵真是有意思!原来竟是这个。。。
好象这个shimid = .. == ..是种很标准的写法,所有编译器都会支持吧?最多有个warring