#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
struct LOCK {
string name;
string type;
vector <string> pids;
};
int main()
{
int segment_id;
LOCK* shared_memory;
struct shmid_ds shmbuffer;
int segment_size;
const int shared_segment_size = 0x6400;
/* Allocate a shared memory segment. */
segment_id = shmget (IPC_PRIVATE, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
/* Attach the shared memory segment. */
shared_memory = (LOCK*) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %p\n", shared_memory);
/* Determine the segment's size. */
shmctl (segment_id, IPC_STAT, &shmbuffer);
segment_size = shmbuffer.shm_segsz;
printf ("segment size: %d\n", segment_size);
/* Write a string to the shared memory segment. */
//sprintf (shared_memory, "Hello, world.");
shared_memory -> name = "task 1";
shared_memory -> type = "read";
(shared_memory -> pids).push_back("12345");
(shared_memory -> pids).push_back("67890");
/* Detach the shared memory segment. */
shmdt (shared_memory);
/* Reattach the shared memory segment, at a different address. */
shared_memory = (LOCK*) shmat (segment_id, (void*) 0x5000000, 0);
printf ("shared memory reattached at address %p\n", shared_memory);
/* Print out the string from shared memory. */
//printf ("%s\n", shared_memory -> name);
cout << "Name of the shared memory: " + shared_memory -> name << endl;
/* Detach the shared memory segment. */
shmdt (shared_memory);
/* Deallocate the shared memory segment. */
shmctl (segment_id, IPC_RMID, 0);
return 0;
}
Tôi nhận được mã từ hướng dẫn về bộ nhớ dùng chung. Nó làm việc cho đến khi tôi định nghĩa struct LOCK và cố gắng viết LOCK thay vì char * vào bộ nhớ chia sẻ.Chương trình bộ nhớ chia sẻ C++ đơn giản được viết trên linux: lỗi phân đoạn
Ai đó có thể giúp tôi tìm ra vấn đề ở đây gây ra lỗi phân đoạn không?
Tìm hiểu để biên dịch với tất cả các cảnh báo được kích hoạt và thông tin gỡ lỗi (ví dụ: 'g ++ Wall -g'). Sau đó, sử dụng trình gỡ lỗi 'gdb' của bạn để tìm ra lỗi SEGV ở đâu. –
nếu sử dụng cấu trúc chuỗi và vectơ giống như trong bộ nhớ dùng chung là cần thiết, cách tốt nhất là sử dụng các mảng tĩnh trong cấu trúc LOCK. – totten