Add parentheses in perror messages
[eleutheria.git] / ipc / mmap.c
blob6f2f2c2b880ec8a771b2fc7a5731a3d889b5175c
1 /*
2 * Compile with:
3 * gcc mmap.c -o mmap -Wall -W -Wextra -ansi -pedantic
4 */
6 #include <fcntl.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <sys/mman.h>
13 /* Function prototypes */
14 void diep(const char *s);
16 int main(int argc, char *argv[])
18 const char *message = "this shall be written to file\n";
19 char *map;
20 int fd;
22 /* Check argument count */
23 if (argc != 2) {
24 fprintf(stderr, "Usage: %s\n", argv[0]);
25 exit(EXIT_FAILURE);
28 /* Open file */
29 if ((fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600)) == -1)
30 diep("open()");
32 /* Stretch the file size to the size of the (mmapped) array of chars */
33 if (lseek(fd, strlen(message) - 1, SEEK_SET) == -1) {
34 close(fd);
35 diep("lseek()");
39 * Something needs to be written at the end of the file to
40 * have the file actually have the new size.
42 if (write(fd, "", 1) != 1) {
43 close(fd);
44 diep("write()");
47 /* mmap() the file */
48 if ((map = (char *)mmap(0, strlen(message),
49 PROT_WRITE,
50 MAP_SHARED, fd, 0)) == MAP_FAILED) {
51 close(fd);
52 diep("mmap()");
55 /* Copy message to mmapped() memory */
56 memcpy(map, message, strlen(message));
58 /* Free the mmaped() memory */
59 if (munmap(map, strlen(message)) == -1) {
60 close(fd);
61 exit(EXIT_FAILURE);
64 /* Close file */
65 close(fd);
67 return EXIT_SUCCESS;
70 void diep(const char *s)
72 perror(s);
73 exit(EXIT_FAILURE);