aboutsummaryrefslogtreecommitdiffstats
path: root/usemem_direct_write.c
blob: 838322a10231a58c4b638d6af0003aee4466095f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#define _GNU_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>

/* needs to be multiple of softblock size of filesystem */
#define SIZE (512 * 32)

void usage(char *command)
{
	fprintf(stderr, "usage: %s FILENAME SIZE\n", command);
	exit(1);
}

int main(int argc, char *argv[])
{
	int fd;
	void *address;

	if (argc != 3) usage(argv[0]);

	if ((fd = open(argv[1], O_CREAT | O_DIRECT | O_RDWR, 0666)) < 0) {
		fprintf(stderr, "ERROR: failed to open `%s': %s \n",
			argv[1], strerror(errno));
		exit(1);
	} else {
		/* Align memory -- required by O_DIRECT flag */
		int ret = posix_memalign(&address, SIZE, SIZE);
		if (ret < 0) {
			close(fd);
			return -1;
		}

		memset(address, atoi(argv[2]), SIZE);

		/* fillup the memory in chunks of SIZE */
		while(write(fd, address, SIZE) > 0){};

		close(fd);
	}

	return 0;

}