void reader(int seq) { cout << "reader " << seq << endl; int shm_id = shmget(SHM_KEY, BUF_SIZE, IPC_CREAT); if (shm_id == -1) { perror("Fail to get shared memory id"); return; // Attach to the segment to get a pointer to it. char* shm_buf = static_cast(shmat(shm_id, NULL, 0)); if (shm_buf == nullptr) { perror("Fail to attach shared memory"); return; /* Transfer blocks of data from shared memory to stdout*/ while (1) { cout << "buf[" << seq << "] = " << shm_buf << endl; if (string(shm_buf) == to_string(seq)) { break; sleep(3); cout << "Detaching shared memory" << endl; if (shmdt(shm_buf) == -1) { perror("Fail to detaching shared memory"); return; void writer() { int shm_id = shmget(SHM_KEY, BUF_SIZE, IPC_CREAT); if (shm_id == -1) { perror("Fail to get shared memory id"); return; // Attach to the segment to get a pointer to it. char* shm_buf = static_cast(shmat(shm_id, NULL, 0)); if (shm_buf == nullptr) { perror("Fail to attach shared memory"); return; /* Transfer blocks of data from shared memory to stdout*/ while (1) { cin >> shm_buf; cout << "Detaching shared memory" << endl; if (shmdt(shm_buf) == -1) { perror("Fail to detaching shared memory"); return; int main(int argc, char* argv[]) { if (argc < 2) { return 0; srand(::time(nullptr)); cout << argv[1] << endl; string argv1 = argv[1]; if (argv1 == "reader") { reader(rand() % 1000); } else { writer(); return 0;
  • 将文件命名为shm_test.cpp,编译后运行
  • ./shm_test reader
    ./shm_test writer
    
  • 可以看到读者能够读取到写者写入的数据
  • 如果报错显示
  • Fail to get shared memory id: Permission denied
  • sudo ./shm_test reader
    sudo ./shm_test writer