gpt4 book ai didi

c++ - shmget shmat 无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:04 25 4
gpt4 key购买 nike

<分区>

    class test_class
{
public:
std::string str;
int ival;
};

int main()
{
int shmkey = 3450;
int shmid;

if((shmid = shmget(shmkey, sizeof(test_class*), IPC_CREAT | 0666)) < 0)
{
perror("shmget");
exit(1);
}

test_class **test_obj;
if((test_obj = (test_class**) shmat(shmid, NULL, 0)) == (test_class**) -1)
{
perror("shmat");
exit(1);
}

test_class* new_obj = new test_class();
*test_obj = new_obj;

(*test_obj)->str = "parent process string";
(*test_obj)->ival = 9;

pid_t pid = fork();

if(pid == 0)
{
int shmkey = 3450;
int shmid;

if((shmid = shmget(shmkey, sizeof(test_class*), 0666)) < 0)
{
perror("shmget");
exit(1);
}

test_class **test_obj;
if((test_obj = (test_class**) shmat(shmid, NULL, 0)) == (test_class**) -1)
{
perror("shmat");
exit(1);
}

(*test_obj)->str = "child process string";
(*test_obj)->ival = 10;

exit(EXIT_SUCCESS);
}

sleep(3);
std::cout << (*test_obj)->str << std::endl;
std::cout << (*test_obj)->ival << std::endl;

shmctl(shmid, IPC_RMID, 0);

return 0;
}


This code output is :-
child process string
9

在这个程序中,我正在更新子进程中的共享内存对象(在堆内存中)并在父进程中打印更新的值。正如我们从输出中看到的那样,它正确地更新了字符串而不是 int。由于它在堆内存中,因此不应更新。此处的字符串如何更新?

有什么帮助吗?

谢谢,高拉夫

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com