日期:2014-05-16  浏览次数:20564 次

shmget(), 共享内存该如何使用
很奇怪的一个问题。   共享内存该如何用

#include   <stdio.h>
#include   <sys/shm.h>
#include   <unistd.h>
#include   <sys/ipc.h>
#include   <errno.h>

int   main(int   argc,   char   **argv)
{
        key_t   key;
        int   shmqid;
        char   *user_buf;
        char   *copy   =   "hello ";

        key   =   ftok( ". ",   't ');

        shmqid   =   shmget(key,   20,   IPC_CREAT)

        if   ((user_buf   =   shmat(shmqid,   0,   0))   <   0)   {
                perror(strerror(errno));
                exit(1);
        }
        /*************************问题在这里***************************/
        //user_buf   =   "hello ";//用这句取代下面的strcpy则下面的进程无法输出这个字符串
        strcpy(user_buf,   copy);   //用strcpy则没有问题,
}


==============================================================
这个进程打印上面的进程写进去的字符串
int   main()
{
        key_t   key   =   ftok( ". ",   'w ');

        char   *user_buf;
        key   =   ftok( ". ",   't ');

        int   shmqid   =   shmget(key,   20,   0);

        //char   *user_buf   =   shmat(shmqid,   0,   0);
        if   ((user_buf   =   shmat(shmqid,   0,   0))   <   0)   {
                perror(strerror(errno));
                exit(1);
        }

        printf( "user_buf:   %x,   read   from   shared   memory:   \n%sEND\n ",   &user_buf,   user_buf);   //上面的用strcpy则可以正常输出,   用user_buf   =   "hello "则不行

}

------解决方案--------------------

user_buf = shmat(shmqid, 0, 0)
user_buf鎸囧悜浜嗗叡浜唴瀛樼殑璧峰鍦板潃銆?
缁忚繃杩欎竴鍙ュ悗:user_buf= "hello "
鎶妘ser_buf鎸囧悜鐨勫湴鍧€鏀逛负璇ヨ繘绋嬩腑鐨勪竴涓瓧绗︿覆甯搁噺銆傚苟娌℃湁淇敼鍏变韩鍐呭瓨涓殑鍐呭銆? 褰撶劧灏卞湪鍙﹀涓€涓繘绋嬩腑鎵撲笉鍑篽ello;

strcpy ( user_buf , "hello ");
杩欎竴鍙ユ槸鎶婂瓧绗︿覆甯搁噺 "hello "澶嶅埗鍒颁簡user_buf鎵€鎸囧悜鐨勭┖闂翠腑銆備慨鏀逛簡鍏变韩鍐呭瓨涓殑鍐呭锛屽綋鐒跺氨鍦ㄥ彟澶栦竴涓繘绋嬩腑鎵撳嚭鏉ヤ簡銆?
鎸囬拡鐨勬蹇佃繕娌$悊瑙i€忥紝澶氱湅鐪嬩功鍚?:)
------解决方案--------------------
鏅曪紝鎬庝箞鍏ㄦ槸涔辩爜锛
------解决方案--------------------
The reason is that:
user_buf = "hello ";
/* This statement changes the user_buf itself */
strcpy(user_buf, copy);
/* This statement changes the contents of the memory that the user_buf pointed to */