如何使用共享内存传递数据并将接收到的数据保存到文件

发布于 2024-12-02 06:06:24 字数 2738 浏览 0 评论 0原文

我是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;
}

I am new to linux environment. I just know the basics of C. I am trying to learn linux programming. For this I am trying an example on shared memory. Please someone help me with this example.
I am trying to send person details (like name, phone number & address) to another process using Shared memory. After receiving the data by the second process, I am trying to save received data into a file. This is the task I am doing.
I am able to send just the name and receive it in the second process. Can someone please help how to send the data(like name, phone number & address) to second process and in the second process it must print the data and it should save the data to a file.
Here is my code:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

2024-12-09 06:06:25

要将数据保存在文件中,可以使用文件流。为此,您必须了解文件流。

希望这些链接会有所帮助。

http://linux.die.net/man/3/fopen

http://en.wikipedia.org/wiki/C_file_input/output

这里是我特别提到的示例程序打字、整理并附上,供大家参考。

#include<sys/types.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h> 

struct mystruct // you can make your own structure if you want to pass many data
{
  int i;
  float f;
  char c;
  int arr[3];
}myObj = {1,1.1,'C',{100,1000,10000}};


main()
{
  int shmid;
  char* addr1;
  key_t key;
  //file to key. Generates a unique key
  key = ftok("/home/muthu/Desktop/anyfile.txt",'T');
  shmid = shmget(key,sizeof(struct mystruct),IPC_CREAT|SHM_R|SHM_W);
  printf("shmid = %d",shmid);
  addr1 = shmat(shmid,0,0);
  printf("\nIPC SHARED MEMORY");
  //copying your structure at the shared location.
  memcpy(addr1,&myObj,sizeof(myObj));
  printf("\nMESSAGE STORED");
}

对于共享内存2......

//<All necessary header files>
//<same my struct declaration here>
main()
{
  int shmid;
  char* addr1;
  FILE* fp;
  key_t key;

  struct mystruct* myObj2;
  //Generate the same unique key. Must provide the same file here too.
  key = ftok("/home/muthu/Desktop/anyfile.txt",'T');
  shmid = shmget(key,sizeof(struct mystruct),SHM_R|SHM_W);
  addr1 = shmat(shmid,0,0);
  myObj2 = (struct mystruct*)malloc(sizeof(struct mystruct)*1);
  if(shmid == -1)
    printf("\nShared memory error");
  //Retrieve the stored information, form the shared location.
  memcpy(myObj2,addr1,sizeof(struct mystruct));
  fp = fopen("/home/muthu/Desktop/MyFile.txt","w"); //open a file stream
  if(fp == NULL) 
    printf("\nError on opening file stream.\n");
  fprintf(fp,"\nIPC SHARED MEMORY");
  fprintf(fp,"\nMESSAGE RECIEVED FORM THE SHARED MEMORY  IS..\n");
  fprintf(fp,"\ninteger: %d",myObj2->i);
  fprintf(fp,"\nfloat: %f",myObj2->f);
  fprintf(fp,"\nchar: %c",myObj2->c); //write to the file
  fprintf(fp,"\narr: %d %d %d",myObj2->arr[0],myObj2->arr[1],myObj2->arr[2]);
  fprintf(fp,"\nDATA RECIEVED.");  
  fclose(fp); //close the file stream
  printf("\nMessage successfully stored!");
}

For saving the data in a file, you can use file stream. For that you have to know about file streams.

Hope these link will help.

http://linux.die.net/man/3/fopen

http://en.wikipedia.org/wiki/C_file_input/output

Here comes the example program which I particularly typed, compiled and attached it for your reference.

#include<sys/types.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h> 

struct mystruct // you can make your own structure if you want to pass many data
{
  int i;
  float f;
  char c;
  int arr[3];
}myObj = {1,1.1,'C',{100,1000,10000}};


main()
{
  int shmid;
  char* addr1;
  key_t key;
  //file to key. Generates a unique key
  key = ftok("/home/muthu/Desktop/anyfile.txt",'T');
  shmid = shmget(key,sizeof(struct mystruct),IPC_CREAT|SHM_R|SHM_W);
  printf("shmid = %d",shmid);
  addr1 = shmat(shmid,0,0);
  printf("\nIPC SHARED MEMORY");
  //copying your structure at the shared location.
  memcpy(addr1,&myObj,sizeof(myObj));
  printf("\nMESSAGE STORED");
}

And for shared memory 2.....

//<All necessary header files>
//<same my struct declaration here>
main()
{
  int shmid;
  char* addr1;
  FILE* fp;
  key_t key;

  struct mystruct* myObj2;
  //Generate the same unique key. Must provide the same file here too.
  key = ftok("/home/muthu/Desktop/anyfile.txt",'T');
  shmid = shmget(key,sizeof(struct mystruct),SHM_R|SHM_W);
  addr1 = shmat(shmid,0,0);
  myObj2 = (struct mystruct*)malloc(sizeof(struct mystruct)*1);
  if(shmid == -1)
    printf("\nShared memory error");
  //Retrieve the stored information, form the shared location.
  memcpy(myObj2,addr1,sizeof(struct mystruct));
  fp = fopen("/home/muthu/Desktop/MyFile.txt","w"); //open a file stream
  if(fp == NULL) 
    printf("\nError on opening file stream.\n");
  fprintf(fp,"\nIPC SHARED MEMORY");
  fprintf(fp,"\nMESSAGE RECIEVED FORM THE SHARED MEMORY  IS..\n");
  fprintf(fp,"\ninteger: %d",myObj2->i);
  fprintf(fp,"\nfloat: %f",myObj2->f);
  fprintf(fp,"\nchar: %c",myObj2->c); //write to the file
  fprintf(fp,"\narr: %d %d %d",myObj2->arr[0],myObj2->arr[1],myObj2->arr[2]);
  fprintf(fp,"\nDATA RECIEVED.");  
  fclose(fp); //close the file stream
  printf("\nMessage successfully stored!");
}
日暮斜阳 2024-12-09 06:06:25

这是您可以使用的片段

fp = fopen("filename","a+");
fwrite(name, 1, strlen(name),fp);
fclose(fp);

Here is a snippet that you can use

fp = fopen("filename","a+");
fwrite(name, 1, strlen(name),fp);
fclose(fp);
寒江雪… 2024-12-09 06:06:25

您可以将所有三个字段存储到一个结构中,并将该结构加载到共享内存中。通过这种方式,您可以确保所有字段都位于一个结构下。

在读取 SHM 的过程中,您可以使用上面其他人提到的文件流实用程序。

You can store all your three fields onto a structure and load the structure onto the Shared Memory. In this way you are assured to have all the fields under one structure.

In the process that reads the SHM you can use the File Stream utils as mentioned above by others.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文