C语言 如何创建一个新的进程,并使用共享内存与之通信



嗨,我正在尝试创建一个应用程序,它需要输入数据"hello world"。我正在使用system()创建一个新进程,并且我想使用共享内存(进程间通信)访问该进程中的application1的数据。我试着运行这个程序,但无法得到输出"hello world"。如何将application1和process1中的共享内存附加到相同的地址位置。请帮我一下。

Application1.c

#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main ()
{
int segment_id;
char* shared_memory;
struct shmid_ds shmbuffer;
int segment_size;
const int shared_segment_size = 0x6400;
/* Allocate a shared memory segment. */
segment_id = shmget (IPC_PRIVATE, shared_segment_size,
                        IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
/* Attach the shared memory segment. */
shared_memory = (char*) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %pn", shared_memory);
/* Determine the segment’s size. */
shmctl (segment_id, IPC_STAT, &shmbuffer);
segment_size = shmbuffer.shm_segsz;
printf ("segment size: %dn", segment_size);
/* Write a string to the shared memory segment. */
sprintf (shared_memory, "Hello, world.");
/* Detach the shared memory segment. */
system("./process1");
shmdt (shared_memory);
shmctl (segment_id, IPC_RMID, 0);
return 0;
}

process1.c

#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main ()
{
int segment_id;
char* shared_memory;
struct shmid_ds shmbuffer;
int segment_size;
const int shared_segment_size = 0x6400;
/* Allocate a shared memory segment. */
segment_id = shmget (IPC_PRIVATE, shared_segment_size,
                        IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
/* Attach the shared memory segment. */
shared_memory = (char*) shmat (segment_id, 0, 0);
printf ("shared memory2 attached at address %pn", shared_memory);
printf ("%sn", shared_memory);
/* Detach the shared memory segment. */
shmdt (shared_memory);
return 0;
}
输出:

shared memory attached at address 0x7f616e4f2000
segment size: 25600
shared memory22 attached at address 0x7f8746d17000

输出没有打印共享内存中的数据。我希望输出为"hello, world"。

谢谢

以下几点:

1) shmget的第一个参数是键。您在两个进程中都使用了IPC_PRIVATE,这意味着它将在两个进程中分配一块"新"共享内存。您需要做的是做出安排,使两个进程使用相同的密钥,但不是IPC_PRIVATE密钥。

2)两个进程中的shared_memory指针不需要是相同的值才能工作。是的,内存是共享的,但这并不意味着指针将具有相同的值。共享内存可以映射到每个进程的不同内存位置

最新更新