Skip to content

Instantly share code, notes, and snippets.

@Mattosx
Created November 26, 2018 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mattosx/1b835342cd8a0d8c55f4ecef239902b1 to your computer and use it in GitHub Desktop.
Save Mattosx/1b835342cd8a0d8c55f4ecef239902b1 to your computer and use it in GitHub Desktop.
process communication via mmap
/*************************************************************************\
* Copyright (C) Michael Kerrisk, 2016. *
* *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation, either version 3 or (at your option) any *
* later version. This program is distributed without any warranty. See *
* the file COPYING.gpl-v3 for details. *
\*************************************************************************/
/* t_mmap.c
Demonstrate the use of mmap() to create a shared file mapping.
*/
#include <sys/mman.h>
#include <fcntl.h>
#include "tlpi_hdr.h"
#define MEM_SIZE 10
int
main(int argc, char *argv[])
{
char *addr;
int fd;
if (argc < 2 || strcmp(argv[1], "--help") == 0)
usageErr("%s file [new-value]\n", argv[0]);
fd = open(argv[1], O_RDWR);
if (fd == -1)
errExit("open");
addr = mmap(NULL, MEM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED)
errExit("mmap");
if (close(fd) == -1) /* No longer need 'fd' */
errExit("close");
printf("Current string=%.*s\n", MEM_SIZE, addr);
/* Secure practice: output at most MEM_SIZE bytes */
if (argc > 2) { /* Update contents of region */
if (strlen(argv[2]) >= MEM_SIZE)
cmdLineErr("'new-value' too large\n");
memset(addr, 0, MEM_SIZE); /* Zero out region */
strncpy(addr, argv[2], MEM_SIZE - 1);
if (msync(addr, MEM_SIZE, MS_SYNC) == -1)
errExit("msync");
printf("Copied \"%s\" to shared memory\n", argv[2]);
}
exit(EXIT_SUCCESS);
}
/*
usage:
$dd if=/dev/zero of=s.txt bs=1 count=1024
1024+0 records in
1024+0 records out
1024 bytes (1.0 kB) copied, 0.002725 s, 376 kB/s
$./t_mmap s.txt hello
Current string=
Copied "hello" to shared memory
$./t_mmap s.txt goodbye
Current string=hello
Copied "goodbye" to shared memory
$od -c -w8 s.txt
0000000 g o o d b y e \0
0000010 \0 \0 \0 \0 \0 \0 \0 \0
*
0002000
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment