2011-08-24 17 views
1

嗨,我正在尝试创建一个接受输入数据“hello world”的application1。我正在使用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 %p\n", shared_memory); 
/* Determine the segment’s size. */ 
shmctl (segment_id, IPC_STAT, &shmbuffer); 
segment_size = shmbuffer.shm_segsz; 
printf ("segment size: %d\n", 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 %p\n", shared_memory); 
printf ("%s\n", 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 

器的输出没有在共享存储器中的打印数据。我想输出打印“你好,世界”。

谢谢

+0

为什么要使用共享内存作为IPC?这是非常艰苦的工作。替代品的数量级更容易。 –

+0

哦真的。这是我第一次在IPC上开展计划,并且我必须涵盖所有IPC,这是我的TL分配给我的工作。 – maddy

回答

1

几件事情:

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

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

+0

这里有更多的错误,但让我们从这开始.... – Erik

+0

如何初始化shm_key。 int shm_key = 10,我可以用shm_key替换IPC_PRIVATE。这是正确的方法。 – maddy

+0

你可以做到这一点。 IPC_CREAT |如果该键已被使用,则IPC_EXCL将导致shmget失败。您应该从process1.c中删除IPC_EXCL。 http://linux.die.net/man/2/shmget另外,这个数字对于整个机器来说是全局的,所以你机器上的其他东西可能已经在使用shm_key = 10了。因此,你需要处理shmget失败(如果它返回-1)。 – Erik

相关问题