linux 共享内存 出错,一个简单的C共享内存程序写在linux上:分段错误

#include

#include

#include

#include

#include

#include

using namespace std;

struct LOCK {

string name;

string type;

vector 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;

}

我从共享内存教程中获取了代码.它一直工作,直到我定义了struct LOCK并尝试将LOCK而不是char *写入共享内存.

有人可以帮我解决导致分段错误的问题吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值