在共享内存进程中分配字符串 [英] Assigning strings in shared memory processes

查看:48
本文介绍了在共享内存进程中分配字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序需要在两个进程之间共享一个字符串.我已经声明了一个包含 *char 数组的结构.在主进程分叉之前,这个结构被分配了 shmgetshmat.

I have a program that needs to share a string between two processes. I have declared a struct that contains an array of *char. This struct is allocated with shmget and shmat before the main process is forked.

typedef struct Queue
{
    int index;
    char *directory[10];
} Queue;

在其中一个进程中,我尝试设置值:(data->dir_name is a *char to a string like "/data1")

In one of the processes, I try to set the value: (data->dir_name is a *char to a string such as "/data1")

queue->directory[i] = data->dir_name; // Option 1
queue->directory[i] = "foo";          // Option 2

我的问题是,上面的第一个和第二个语句有什么区别?当将 queue->directory[i] 设置为 "foo" 时,其他进程看到了.然而,传递值data->dir_name,它不会.

My question is, what is the difference between the first and second statements above? When setting the queue->directory[i] to "foo", the other process sees it. However, passing the value data->dir_name, it does not.

提前致谢!

推荐答案

问题是你只是分配一个指针,而不是复制字符串数据.在第一种情况下,您将值设置为指向第二个进程看不到的内存.当你做第一行时,指针data->dir_name被放入queue->directory[i],但是当另一个进程查看那个内存地址时在它自己的内存空间内,数据不在那里.另一方面,第二行将静态字符串 "foo" 的地址放入变量中.由于进程是从同一个源编译的,所以这个字符串在每个进程的内存中都处于相同的位置,所以第二个可以看到它.

The problem is you are only assigning a pointer, not copying the string data. In the first case you are setting the value to point to memory that the second process can't see. When you do the first line, the pointer data->dir_name is put into queue->directory[i], but when the other process looks at that memory address within its own memory space, the data is not there. On the other hand, the second line puts the address of the static string "foo" into the variable. Since the processes are compiled from the same source, that string is in the same place in each process's memory, so the second one can see it.

您想要做的是在结构中拥有一个缓冲区,strcpy 将目录名称放入其中.你需要

What you want to be doing is having a buffer in the struct that you strcpy the directory name into. You'll need

char directory[10][200];

strcpy (queue->directory[i], data->dir_name);

您需要检查字符串长度是否小于 200(在本例中),如果太长则报告相应的错误.我不熟悉共享内存函数以确切知道如何执行 malloc 等效项;如果你能做到的话;然后您将字符串复制到 malloc ed 共享内存中,并将指向它的指针放入一个数组中,就像您在代码中一样.不过,从非常快速的 Google 搜索来看,像这样 malloc 共享内存似乎效果不佳.

You'll want to check that the string length is less than 200 (in this case), and report an appropriate error if it's too long. I'm not familiar with shared memory functions to know exactly how to do a malloc equivalent; if you could do that; then you would copy the string into the malloced shared memory and put the pointer to it in an array like you have in your code. From a very quick Google search though, it appears that mallocing shared memory like this might not work very well.

这篇关于在共享内存进程中分配字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆