几种IPC机制可用于POSIX系统,包括共享内存和消息传递。在这里,我们探索共享内存的POSIX API。
POSIX共享内存是使用内存映射文件来组织的,这些文件将共享内存区域与文件相关联。进程必须首先使用shm_open()系统调用创建共享内存对象,如下所示:
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
Parameters:
name: The first parameter specifies the name of the shared-memory object.
Processes that wish to access this shared memory must refer to the
object by this name.
O_CREAT | O_RDWR : The subsequent parameters specify that the shared-memory
object is to be created if it does not yet exist (O_CREAT) and that the object is
open for reading and writing (O_RDWR).
The last parameter establishes the directory permissions of the
shared-memory object.
成功调用shm_open()将为共享内存对象返回一个整数文件描述符。建立对象后,ftruncate()函数用于配置对象的大小(以字节为单位)。通话
ftruncate(shm_fd, 4096);
将对象的大小设置为4,096字节。最后,mmap()函数建立一个包含共享内存对象的内存映射文件。它还返回指向用于访问共享内存对象的内存映射文件的指针。
显示面向生产者和消费者的POSIX共享内存API的程序
C program for Producer process illustrating POSIX shared-memory API.
#include
#include
#include
#include
#include
#include
int main()
{
/* the size (in bytes) of shared memory object */
const int SIZE = 4096;
/* name of the shared memory object */
const char* name = "OS";
/* strings written to shared memory */
const char* message_0 = "Hello";
const char* message_1 = "World!";
/* shared memory file descriptor */
int shm_fd;
/* pointer to shared memory obect */
void* ptr;
/* create the shared memory object */
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
/* configure the size of the shared memory object */
ftruncate(shm_fd, SIZE);
/* memory map the shared memory object */
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
/* write to the shared memory object */
sprintf(ptr, "%s", message_0);
ptr += strlen(message_0);
sprintf(ptr, "%s", message1);
ptr += strlen(message_1);
return 0;
}
// C program for Consumer process illustrating
// POSIX shared-memory API.
#include
#include
#include
#include
#include
int main()
{
/* the size (in bytes) of shared memory object */
const int SIZE = 4096;
/* name of the shared memory object */
const char* name = "OS";
/* shared memory file descriptor */
int shm_fd;
/* pointer to shared memory object */
void* ptr;
/* open the shared memory object */
shm_fd = shm_open(name, O_RDONLY, 0666);
/* memory map the shared memory object */
ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
/* read from the shared memory object */
printf("%s", (char*)ptr);
/* remove the shared memory object */
shm_unlink(name);
return 0;
}
上面的程序在实现共享内存时使用了生产者-消费者模型。
- 生产者建立共享内存对象并写入共享内存,而使用者从共享内存中读取。
- 生产者创建一个名为OS的共享内存对象,并编写著名的字符串“ Hello World!”。共享内存。
- 程序内存映射一个指定大小的共享内存对象,并允许写入该对象。 (显然,生产者只需要写作即可。)
- 标记MAP SHARED指定对共享内存对象的更改将对所有共享对象的进程可见。注意,我们通过调用sprintf()函数并将格式化后的字符串写入指针ptr来写入共享内存对象。
- 每次写入后,我们必须将指针增加写入的字节数。使用者进程读取并输出共享内存的内容。
- 使用者还调用shm_unlink()函数,该函数在使用者访问共享存储器段之后将其删除。
参考
Silberschatz的操作系统概念