Merge branch 'exp-hash'
[eleutheria.git] / ipc / mmap.c
blobfa4a188f796e61ace674a4952998188d1a2468ce
1 #include <fcntl.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <sys/mman.h>
8 /* function prototypes */
9 void diep(const char *s);
11 int main(int argc, char *argv[])
13 const char *message = "this shall be written to file\n";
14 char *map;
15 int fd;
17 /* check argument count */
18 if (argc != 2) {
19 fprintf(stderr, "Usage: %s\n", argv[0]);
20 exit(EXIT_FAILURE);
23 /* open file */
24 if ((fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600)) == -1)
25 diep("open");
27 /* stretch the file size to the size of the (mmapped) array of chars */
28 if (lseek(fd, strlen(message) - 1, SEEK_SET) == -1) {
29 close(fd);
30 diep("lseek");
33 /* something needs to be written at the end of the file to
34 have the file actually have the new size */
35 if (write(fd, "", 1) != 1) {
36 close(fd);
37 diep("write");
40 /* mmap() the file */
41 if ((map = (char *)mmap(0, strlen(message), PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) {
42 close(fd);
43 diep("mmap");
46 /* copy message to mmapped() memory */
47 memcpy(map, message, strlen(message));
49 /* free the mmaped() memory */
50 if (munmap(map, strlen(message)) == -1) {
51 close(fd);
52 exit(EXIT_FAILURE);
55 /* close file */
56 close(fd);
58 return EXIT_SUCCESS;
61 void diep(const char *s)
63 perror(s);
64 exit(EXIT_FAILURE);