Using shmget in C to allocate shared memory
shmget
This article will demonstrate various ways to allocate shared memory in C
using the function.
shmget
Allocating shared memory in C
using
Shared memory is one of the ways of inter-process communication, which allows two or more processes to exchange data and communicate quickly in user space. Shared memory means that multiple processes share the same area in memory, and they can modify/access this memory as needed.
In the following examples, we will demonstrate an interface called System V shared memory, which is provided by four functions: shmget
, shmat
, shmdt
and shmctl
.
-
shmget
Used to create a new shared memory segment or retrieve the identifier of an already created memory segment. -
shmat
Call is used to attach the given shared memory segment to the memory space of the calling process. -
shmdt
Can be used to detach a given memory segment. -
shmctl
Used to modify and reallocate segments with multiple options.
The next example code implements basic use of the shmget
and shmat
functions for a process that creates a new shared segment and then writes some text to it. shmget
The functions require three parameters, the first of which is the key of the memory segment. The key value can be the macro if a new segment needs to be created, or IPC_PRIVATE
the key of an existing segment if the identifier of the memory needs to be obtained by calling . shmget
The second parameter of specifies the size of the segment, and the third parameter is the permission flags, which can be ORed to contain multiple values.
Once the memory segment is created, the segment identifier is obtained and can be passed to shmat
the __addr__ function to attach the given memory. The user can pass the specific address of a given memory segment as the second argument to __addr__ shmat
. However, it is common to let the kernel choose the address and specify __addr__ NULL
to indicate this.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/shm.h>
enum {SEGMENT_SIZE = 0x6400};
const char *data = "Hello there!";
int main(int argc, char *argv[]) {
int status;
int segment_id;
segment_id = shmget (IPC_PRIVATE, SEGMENT_SIZE,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
char *sh_mem = (char *) shmat(segment_id, NULL, 0);
printf("Segment ID %d\n", segment_id);
printf("Attached at %p\n", sh_mem);
memmove(sh_mem, data, strlen(data)+1);
printf("%s\n", sh_mem);
shmdt(sh_mem);
shmctl(segment_id, IPC_RMID, 0);
exit(EXIT_SUCCESS);
}
Output:
Segment ID 1540195
Attached at 0x7f6ba1437000
Hello there!
Once shmat
the function returns a valid pointer, we can treat it as any memory address and operate on it as needed. Finally, call the shmdt
and shmctl
functions to detach the given segment and reallocate the memory. Assume that shmctl
no call is made to the allocated memory segments. In this case, they will remain in the system's memory after the program terminates and may hit the limit on the total number of shared memory segments in the whole system.
On the other hand, the following sample code demonstrates how two processes can interact using shared memory. The code is the same as the previous example, except that after printing Hello there!
the string, the main process is forked and a child process is created that stores a different string into the same address. At the same time, the parent process is paused, waiting for the child process to terminate and exit with a success code; the newly stored string is printed to the console. If multiple processes need to modify and access a shared memory segment at the same time, the programmer needs to employ some synchronization tools, such as semaphores.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <pthread.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/shm.h>
enum {SEGMENT_SIZE = 0x6400};
const char *data = "Hello there!";
int main(int argc, char *argv[]) {
int status;
int segment_id;
segment_id = shmget (IPC_PRIVATE, SEGMENT_SIZE,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
char *sh_mem = (char *) shmat(segment_id, 0, 0);
printf("Segment ID %d\n", segment_id);
printf("Attached at %p\n", sh_mem);
memmove(sh_mem, data, strlen(data)+1);
printf("%s\n", sh_mem);
pid_t child_pid = fork();
if (child_pid == -1)
perror("fork");
if (child_pid == 0) {
strcpy(sh_mem, "NEW DATA Stored by Child Process\0");
printf("child pid - %d\n", getpid());
exit(EXIT_SUCCESS);
} else {
pid_t ret = waitpid(child_pid, &status, WUNTRACED | WCONTINUED);
if (ret == -1)
perror("waitpid");
if (WIFEXITED(status))
printf("Child exited, status - %d\n", WEXITSTATUS(status));
if (WEXITSTATUS(status) == 0)
printf("%s\n", sh_mem);
}
shmdt(sh_mem);
shmctl(segment_id, IPC_RMID, 0);
exit(EXIT_SUCCESS);
}
Output:
Segment ID 1540195
Attached at 0x7fd825a25000
Hello there!
child pid - 27291
Child exited, status - 0
NEW DATA Stored by Child Process
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Flushing stdout output stream in C
Publish Date:2025/04/17 Views:200 Category:C语言
-
stdout This article will demonstrate various methods on how to flush an output stream in C language . Use function in C language fflush to refresh stdout output stream I/O The C standard library provides a stdio buffered version of the I/O
Using the feof function in C language
Publish Date:2025/04/17 Views:87 Category:C语言
-
feof This article will introduce several ways to use functions in C language . Use feof the function to check the end-of-file indicator on a file stream in C language feof The function is part of the C standard input/output library and is d
Use the C language setenv function to access environment variables
Publish Date:2025/04/17 Views:122 Category:C语言
-
setenv This article will introduce several methods of using functions to export environment variables in C language . setenv Use function to export environment variables in C language Every program running on a Unix-base system has an envir
How to get the size of an array in C
Publish Date:2025/04/17 Views:62 Category:C语言
-
This tutorial explains how to determine the length of an array in C. sizeof() The operator is used to get the size/length of an array. sizeof() Operator determines the size of an array in C sizeof() The operator is a compile time unary oper
Initialize array to 0 in C
Publish Date:2025/04/17 Views:133 Category:C语言
-
This article explains how to initialize an array to 0 in C language. The declaration of an array in C language is as follows. char ZEROARRAY[ 1024 ]; It becomes all zeros at runtime in the global scope. If it is a local array, there is a si
Structure arrays in C
Publish Date:2025/04/17 Views:188 Category:C语言
-
This tutorial explains how to create a structure array in C language, which is a collection of multiple structure variables, each of which contains information about a different entity. Structure arrays in C An array is a sequential collect
Printing Character Array in C
Publish Date:2025/04/17 Views:106 Category:C语言
-
This article will introduce various methods on how to print character array in C language. for How to use loop to print character array in C language If we want to print array elements individually and format the output with more details, f
Clearing a character array in C
Publish Date:2025/04/17 Views:119 Category:C语言
-
This article will introduce several methods to clear character arrays in C language. memset Use function to clear char array in C language memset The _set_storage_region function is commonly used to set a storage area to a constant value. T
Initializing character array in C
Publish Date:2025/04/17 Views:92 Category:C语言
-
This article will demonstrate various ways of initializing a character array in C language. {} Initializing a character array in C using curly brace list notation Character arrays are mostly declared as a fixed-size structure and are often