打印

求助:我这个内存共享的小程序,编译没错,运行有错,请各位大哥

求助:我这个内存共享的小程序,编译没错,运行有错,请各位大哥

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

#define BUF_SIZE 1024
#define MYKEY 24

int main(void)
{
            int shmid;
            char *shmptr;
   
            if(shmid=shmget(MYKEY, BUF_SIZE, IPC_CREAT)==-1) //开辟
            {
                printf("shmget error! \n");
                exit(1);
            }
   
        if((shmptr=shmat(shmid,0,0))==( void*)-1)  //附加
        {
                    fprintf(stderr,"shmat error!\n");
                    exit(1);
        }

        while(1)
        {
                    printf("string: %s \n", shmptr);
                    sleep(3000);
        }

        exit(0);
}

[root@localhost linuxc]# gcc -o a24 a24.c
[root@localhost linuxc]# ./a24
shmat error!

各位大哥,这是什么原因啊?

谢谢!

TOP

if((shmptr=shmat(shmid,0,0))==( void*)-1) //附加
{
fprintf(stderr,"shmat error!\n");
exit(1);
}
---------------------
不是-1 是null

另外,出错,你的两个报错,都是一样的,是个不好的习惯。

再拿出的错都不知道~~~~

加一句
printf("the errno=[%d]",errorno);
看看报什么错

TOP

谢谢 大哥!

TOP