Cosmetic stuff
[eleutheria.git] / ipc / mmap.c
blobca86e84e4b485bd10e7501009af108c34fdba06a
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
36 if (write(fd, "", 1) != 1) {
37 close(fd);
38 diep("write");
41 /* mmap() the file */
42 if ((map = (char *)mmap(0, strlen(message), PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) {
43 close(fd);
44 diep("mmap");
47 /* Copy message to mmapped() memory */
48 memcpy(map, message, strlen(message));
50 /* Free the mmaped() memory */
51 if (munmap(map, strlen(message)) == -1) {
52 close(fd);
53 exit(EXIT_FAILURE);
56 /* Close file */
57 close(fd);
59 return EXIT_SUCCESS;
62 void diep(const char *s)
64 perror(s);
65 exit(EXIT_FAILURE);