代码之家  ›  专栏  ›  技术社区  ›  Mi Po

在C++中使用共享内存时的错误

  •  0
  • Mi Po  · 技术社区  · 5 年前

    在夜间运行期间,进程崩溃 SIGSEGV 错误。

    strcpy(str, in_string); 在发送应用程序中

    什么会导致这种类型的碰撞?

    #pragma once
    
    #include <iostream> 
    #include <sys/ipc.h> 
    #include <sys/shm.h> 
    #include <stdio.h> 
    
    class LocalSocket {
    public:
    
        LocalSocket() 
        {         // ftok to generate unique key 
            key_t key = ftok("shmfile", 65); 
    
            // shmget returns an identifier in shmid 
            shmid = shmget(key, 1024, 0666 | IPC_CREAT); 
    
            // shmat to attach to shared memory 
            str = (char*) shmat(shmid, (void*)0, 0); 
        }
    
        ~LocalSocket()
        {   
            //detach from shared memory  
            shmdt(str); 
    
            // destroy the shared memory 
            shmctl(shmid, IPC_RMID, NULL); 
        }
    
        int shmid;
        char *str;   
    
        bool Send(char* in_string)
        {
            strcpy(str, in_string);
    
            printf("Data written in memory: %s\n", str); 
    
    
            return true;
        }
    
        bool Receive(char* out_string)
        {   
            printf("Data read from memory: %s\n", str); 
    
            strcpy(out_string, str);
    
            return true;
        }
    };
    
    0 回复  |  直到 5 年前