【发布时间】:2011-11-07 20:51:13
【问题描述】:
我是 linux 环境的新手。我只知道 C 的基础知识。我正在尝试学习 linux 编程。为此,我正在尝试共享内存的示例。请有人帮我这个例子。 我正在尝试使用共享内存将人员详细信息(如姓名、电话号码和地址)发送到另一个进程。通过第二个进程接收数据后,我试图将接收到的数据保存到文件中。这是我正在做的任务。 我可以只发送名称并在第二个过程中接收它。有人可以帮助如何将数据(如姓名、电话号码和地址)发送到第二个进程,并且在第二个进程中它必须打印数据并且应该将数据保存到文件中。 这是我的代码:
address.c
char *shared_memory;
int main()
{
int select;
int segment_id;
char* shared_memory;
int segment_size;
key_t shm_key;
const int shared_segment_size = 0x6500;
shm_key = ftok("/home/madan/programs/shm_tok",'C');
if(shm_key < 0) {
printf("failed to create the key %s\n",strerror(errno));
}
/* Allocate a shared memory segment. */
segment_id = shmget (shm_key, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
if(segment_id < 0) {
printf("error geting the segment id %s\n",strerror(errno));
}
printf("segment ID:%d\n", segment_id);
/* Attach the shared memory segment. */
shared_memory = (char*) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %p\n", shared_memory);
/* I want to send these details to the shared memory. Can someone suggest me the correct way to send these details to shared memory so that second process can retrieve them*/
sprintf(shared_memory, "maddy\n");
sprintf(shared_memory, "767556686");
sprintf(shared_memory, "Ontario");
system("./address-insert");
/* Detach the shared memory segment. */
shmdt (shared_memory);
/
* Deallocate the shared memory segment.*/
shmctl (segment_id, IPC_RMID, 0);
}
addres-insert.c
int main ()
{
int segment_id;
char* shared_memory;
FILE *fp;
char *name;
int segment_size;
key_t shm_key;
shm_key = ftok("/home/madan/programs/shm_tok",'C');
const int shared_segment_size = 0x6500;
/* Allocate a shared memory segment. */
segment_id = shmget (shm_key, shared_segment_size,
S_IRUSR | S_IWUSR);
if(segment_id < 0) {
printf("error:[%s]",strerror(errno));
}
printf("segment id %d\n",segment_id);
/* Attach the shared memory segment. */
shared_memory = (char*) shmat (segment_id, 0, 0);
if(shared_memory == NULL) {
printf("failed to attach the shared memory %s",strerror(errno));
}
printf ("shared memory2 attached at address %p\n", shared_memory);
/* printing the data from shared memory send by first process*/
printf ("name=%s\n", shared_memory);
/*copying the data in shared memory so i can save them to a file*/
strcpy(name, shared_memory);
printf("%s", name);
/*here i have to save the data to a file. But i don't know how to do it, can someone help me with this please*/
/* Detach the shared memory segment. */
shmdt (shared_memory);
return 0;
}
【问题讨论】:
-
共享内存是一种相当笨拙的方式来做这样的事情。您会发现使用命名管道要简单得多。然后您可以串行发送数据项。管道将处理您必须使用共享内存手动执行的所有同步问题。
-
如果您要使用共享内存,请阅读有关现代方式的书籍或教程,而不是阅读使用旧 SysV
shmget接口的 1980 年代 X11 源代码...跨度> -
我们不能一次将数据序列(如姓名、电话号码和地址)发送到共享内存,并且应该由另一个进程接收。
-
strcpy(name, shared_memory); printf("%s", 名称);我想将数据从 shared_memory 复制到一个变量。我可以这样做吗。这是将数据从 shared_memory 复制到变量名的正确方法吗?
-
amardeep & R.. 谢谢
标签: c linux file process shared-memory