我试图在两个进程之间进行通信。我试图在一个进程中将数据(如姓名、电话号码、地址)保存到共享内存中,并试图通过另一个进程打印该数据。
过程1.c
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main ()
{
int segment_id;
char* shared_memory[3];
int segment_size;
key_t shm_key;
int i=0;
const int shared_segment_size = 0x6400;
/* Allocate a shared memory segment. */
segment_id = shmget (shm_key, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
/* Attach the shared memory segment. */
shared_memory[3] = (char*) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %p\n", shared_memory);
/* Write a string to the shared memory segment. */
sprintf(shared_memory[i], "maddy \n");
sprintf(shared_memory[i+1], "73453916\n");
sprintf(shared_memory[i+2], "america\n");
/*calling the other process*/
system("./process2");
/* Detach the shared memory segment. */
shmdt (shared_memory);
/* Deallocate the shared memory segment.*/
shmctl (segment_id, IPC_RMID, 0);
return 0;
}
过程2.c
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main ()
{
int segment_id;
char* shared_memory[3];
int segment_size;
int i=0;
key_t shm_key;
const int shared_segment_size = 0x6400;
/* Allocate a shared memory segment. */
segment_id = shmget (shm_key, shared_segment_size,
S_IRUSR | S_IWUSR);
/* Attach the shared memory segment. */
shared_memory[3] = (char*) shmat (segment_id, 0, 0);
printf ("shared memory22 attached at address %p\n", shared_memory);
printf ("name=%s\n", shared_memory[i]);
printf ("%s\n", shared_memory[i+1]);
printf ("%s\n", shared_memory[i+2]);
/* Detach the shared memory segment. */
shmdt (shared_memory);
return 0;
}
但我没有得到想要的结果。
我得到的结果是:
shared memory attached at address 0x7fff0fd2d460
Segmentation fault
任何人都可以帮我。这是初始化
shared_memory[3]
的正确方法吗?谢谢您。
最佳答案
char* shared_memory[3];
...
shared_memory[3] = (char*) shmat (segment_id, 0, 0);
您将
shared_memory
声明为一个数组,该数组能够保存到char的三个指针,但实际上您要做的是将指针写在数组末尾后面的一个位置。由于不知道内存的其他用途,接下来发生的事情通常是不可预测的。当您试图使用
shared_memory[0]
到shared_memory[2]
中的指针时,事情会变得非常糟糕,因为这些指针从未初始化过。它们充满了堆栈中毫无意义的垃圾——因此出现了分段错误。一般来说,似乎无法区分数组及其元素。在尝试使用共享内存ipc之前,您应该先使用顺序代码中的数组和指针,使自己更加适应。
注意,共享内存是一种更容易出错的ipc方法。除非有严格的效率约束,并且要交换大量数据,否则使用管道、命名管道或套接字要容易得多。