-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathdevzero.c
100 lines (92 loc) · 1.96 KB
/
devzero.c
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2000-2003 Silicon Graphics, Inc.
* All Rights Reserved.
*/
#include "global.h"
int
main(int argc, char **argv)
{
off_t offset = 0;
int blksize = 4096;
long long maxblks = -1; /* no limit */
long long nblks = 0;
int value = 0;
int sts = 0;
int fd;
char *z;
char *path;
int oflags = O_WRONLY;
char *progname;
if (strrchr(argv[0],'/'))
progname = strrchr(argv[0],'/')+1;
else
progname = argv[0];
while ((fd = getopt(argc, argv, "b:n:o:v:ct")) != EOF) {
switch (fd) {
case 'b':
blksize = atoi(optarg) * 512;
break;
case 'n':
maxblks = atoll(optarg);
break;
case 'o':
offset = atoll(optarg);
break;
case 'v':
value = atoi(optarg);
break;
case 'c':
oflags |= O_CREAT;
break;
case 't':
oflags |= O_TRUNC;
break;
default:
sts++;
}
}
if (sts || argc - optind != 1) {
fprintf(stderr,
"Usage: %s [-b N*512] [-n N] [-o off] [-v val] "
" [-c] [-t] <dev/file>\n",
progname);
fprintf(stderr," -c: create -t: truncate\n");
exit(1);
}
path = argv[optind];
if ((fd = open(path, oflags, 0600)) < 0) {
fprintf(stderr,
"error opening \"%s\": %s\n",
path, strerror(errno));
exit(1);
}
if ((lseek64(fd, offset, SEEK_SET)) < 0) {
fprintf(stderr, "%s: error seeking to offset %llu "
"on \"%s\": %s\n",
progname, (unsigned long long)offset, path, strerror(errno));
exit(1);
}
if ((z = memalign(getpagesize(), blksize)) == NULL) {
fprintf(stderr, "%s: can't memalign %u bytes: %s\n",
progname, blksize, strerror(errno));
exit(1);
}
memset(z, value, blksize);
errno = 0;
for (;;) {
if (nblks++ == maxblks)
break;
if ((sts = write(fd, z, blksize)) < blksize) {
if (errno == ENOSPC || sts >= 0)
break;
fprintf(stderr, "%s: write failed: %s\n",
progname, strerror(errno));
break;
}
}
printf("Wrote %.2fKb (value 0x%x)\n",
(double) ((--nblks) * blksize) / 1024, value);
free(z);
return 0;
}