-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathmain.c
1795 lines (1289 loc) · 54.2 KB
/
main.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Cheat on the POSIX C API.
The POSIX C API is mostly an extension of the ANSI C API.
ANSI C features shall not be discussed here.
# Implementations
On most Linux systems as of 2013, the POSIX C API is implemented by the GNU C library:
<http://www.gnu.org/software/libc/>.
The GNU documentation states that POSIX compliance
is a design goal of the GNU C library.
# windows
TODO Is there a Windows implementation for the POSIX C API? Official?
*/
#include "common.h"
int main(void) {
/*
# Namespace
POSIX adds many further per header reserved names which it would be wise to follow even on ANSI C:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html> section "The Name Space"
*/
/*
# errors
Typical error dealing conventions POSIX are:
- if the return value is not needed, functions return 0 on successs and either -1 on failure
or an integer which indicates failure cause
- if the return value is strictly positive, return -1 on error
- if the return value is a pointer, return `NULL` on error
- if the return value can be any integer (`ptrace` for example), return `-1`, but force the user to
clear `errno` before making the call, and check if `errno != -` after the call.
Whenever there is an error, set `errno` accordingly to determine what was the cause of the erro
# errno.h
Is defined by ANSI C, but more predefined error constants are added extended in POSIX,
Only differences from ANSI C shall be commented here. Note that errno,
perror and strerror for example are all in ANSI C.
Some of the POSIX specific errors and their error messages are:
- `EPERM`: Operation not permitted
When users try to do something which requires previledges that they don't have,
such as being the root user.
- `ENOENT`: No such file or directory
- `EINTR`: Interrupted system call
- `EIO`: I/O Error
- `EBUSY`: Device or resource busy
- `EEXIST`: File exists
- `EINVAL`: Invalid argument
- `EMFILE`: Too many open files
- `ENODEV`: No such device
- `EISDIR`: Is a directory
- `ENOTDIR`: Isn’t a directory
Functions that modify errno document that. The convention is that only functions which fail modify
errno, not those that succeed.
errno can be modified as `errno = 0` for example.
*/
{
/*
# errno
`errno` can be modified by functions to contain a description of certain
standard errors.
`errno` is a lvalue and users can explicitly modify it.
This is necessary in certain error checking situations, when the error can only be decided
by changes in errno and not by the return value.
`0` indicates no `error` (ANSI C).
Since many function may change errno, you must use the functions that
depend on errno immediatelly after the function that generates the error.
*/
{
char *dirname = "i_dont_exist";
/* Assure that dirname does not exist. */
if(access(dirname, F_OK) == 0)
assert(rmdir(dirname) != -1);
errno = 0;
rmdir(dirname);
assert(errno != 0);
/* Successful calls do *not* set errno to 0. */
mkdir(dirname, 0777);
rmdir(dirname);
assert(errno != 0);
}
}
/*
# printf
This discusses `printf` and `sprintf` POSIX extensions to ANSI.
*/
{
/*
# dollar
`%2$d` means: use second argument. Treat the following arguments as if this one did not exist.
Has been incorporated in POSIX, but may break ANCI C code! (unlikely).
For that reason, compiling this generates warnings on gcc, and you should avoid this feature as:
- it is unlikely to be incorporated in ANSI C since it is a breaking change
- if you ever decide to increase portability to ANSI C
(in case some other key functions you were using someday get ANSI C alternatives),
you will have to correct this
*/
{
/*
char buf[256];
sprintf(buf, "%2$d %d %d", 0, 1);
assert(strcmp(buf, "1 0 1") == 0);
*/
}
}
/*
# math.h
The `M_PI` constants are defined by POSIX inside of `math.h`.
*/
{
/* # constants */
{
/* ANSI C way of calculating some constants. */
const float PI = acos(-1);
const float E = exp(1);
/* POSIX provides macros that expand to those constants. */
assert(fabs(M_E - E ) < 1e-6);
assert(fabs(M_PI - PI ) < 1e-6);
assert(fabs(M_PI/2.0 - M_PI_2) < 1e-6);
assert(fabs(M_PI/4.0 - M_PI_4) < 1e-6);
}
/*
# bessel
As of POSIX 7, the only major function addition to the math library
seems to be Bessel functions.
TODO understand, specially why is it so important to be here?
http://en.wikipedia.org/wiki/Bessel_function
*/
{
/*
double j0(double);
double j1(double);
double jn(int, double);
*/
}
}
/*
# string functions
POSIX offers some extra convenience functions to common string
operations which are not present in ANSI C.
*/
{
/*
# strfmon
Monetary string formatting.
*/
{
const int size = 16;
char out[size];
strfmon(out, size, "%n", 1234.567);
printf("%s", out);
assert(strcmp(out, "1234.57") == 0);
}
}
/*
# strings.h
*/
{
/*
# ffs
Find First bit Set.
Has assembly support in many processors, e.g. `bsf` in x86.
https://en.wikipedia.org/wiki/Find_first_set
*/
{
assert(ffs(0) == 0);
assert(ffs(1) == 1);
assert(ffs(2) == 2);
assert(ffs(3) == 1);
}
}
/*
# File IO
# File descriptors
`int` identifier to a data stream.
Many file descriptors can point to a single file.
One very important property of file descriptors is the current position from which read and write shall operate.
Reads and writes move the current position forward.
# File descriptors vs ANSI C FILE objects
ANSI C supports only the concept of file pointers via the `FILE` macro.
POSIX extends ANSI C and contains both function that manipulate ANSI C `FILE` objects
and file descriptors, which are integers that identify a file descriptor for the OS.
Operations that use file desriptors:
- open, close, write
Operations that use FILE pointers:
- ANSI C `fopen`, `fclose`, `ftell`, etc. functions
Since they are specific to POSIX, functions that use file pointers often give more options
than ANSI C functions that use `FILE*` objects.
If you don't need that greater level of control,
just use the ANSI C functions for greater portability.
It is possible to convert freely to and from `FILE*` via fdopen and fileno.
# fdopen
Convert file descriptor to `FILE*`.
# fileno
Convert `FILE*` to file descriptor.
# open
man 2 open
Open file descriptors such as files
Returns an `int` (file descriptor number) instead of a file.
Interfaces:
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
Flags. Must specify one and only of the following:
- `O_WRONLY`: write only
- `O_RDONLY`: read only.
Undefined behaviour with O_TRUNC.
TODO can be used with O_CREAT?
- `O_RDWR`: read and write
Other important flags.
- `O_APPEND`: If the file exists, open fd at the end of the file.
- `O_TRUNC`: If the file exists, open fd at the end of the file,
set its length to zero, discarding existing contents.
Undefined behaviour with O_RDONLY.
- `O_CREAT`: If the file does not exit, creat it, with permissions given in mode.
Mode must be specified when this flag is set, and is ignored if this is not set.
- `O_EXCL`: Used with O_CREAT, ensures that the caller creates the file.
The open is atomic; that is, no two opens can open at the same time.
If the file already exists, open will fail.
Useful if multiple programs may try to create the same file.
Mode can be specified via oring predefine permission values of type:
- S_IRWXU 00700 user (file owner) has read, write and execute permission
- S_IRUSR 00400 user has read permission
- S_IWUSR 00200 user has write permission
- S_IXUSR 00100 user has execute permission
For group and other: G and GRP, O and OTH.
Return value: `-1` on error and set perror.
# creat
Same as:
open(path, O_WRONLY|O_CREAT|O_TRUNC, mode);
# close
File descriptors occupy memory and are thus a finite resource.
When you are done with one, release it with a close call.
# write
Write to file descriptor, such as one representing a file gotten via `open`
or one representing a pipe obtained with `pipe`.
Increments the current position of the file descriptor.
For regular files, if this becomes greater than the current file size,
then the file size is increased as needed.
# return value
Returns number of bytes writen.
For regular files, POSIX does not say much when the number of bytes writen is less than the ammount required
and that usually only happens in bad cases:
- signal received in the middle of a write
If it receives a signal before writing anything, returns -1.
- no more space in the filesystem
- no permission to write such large files
For pipes, this may occur in less bad scenarios, for example if the pipe buffer is filled,
the write may either:
- be partial if `nbytes > PIPE_BUF`
- block until more space is available depending on the `O_NONBLOCK` state.
On error, return -1 and set errno.
It seems that POSIX does not say if zero return values on non-zero size write requests.
It is unlikely that an implementation will return 0, since that would make no progress,
and it should return `-1` and set errno instead to report error cases.
# atomicity of simultaneous writes
Writes of less than `PIPE_BUF` bytes cannot be interleaved with other writes.
Larger writes can.
TODO0 are writes to seekable files atomic? Seems not: <http://stackoverflow.com/questions/10650861/atomicity-of-write2-to-a-local-filesystem>
for pipes we know yes for writes smaller than PIPE_BUF.
# pwrite
Same as write, but writes to a given offset and does not update fd position.
It cannot be done on non seekable files.
# read
POSIX 7 docs: http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html
Read bytes from a file descriptor.
Interface:
ssize_t read(int fildes, void *buf, size_t nbyte);
The behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified.
If the starting position is at or after the end-of-file, 0 shall be returned.
If the value of `nbyte` is larger than {SSIZE_MAX}, the result is implementation-defined.
In practice this is rarely the case, because `SSIZE_MAX` is the size of a `size_t` type,
which is usually an integer, giving around 2Gb.
The exact behaviour of read depends on the fd type: pipes and regular files have slightly different rules.
# read pipe
When attempting to read from an empty pipe or FIFO:
- If no process has the pipe open for writing, read() shall return 0 to indicate end-of-file.
- If some process has the pipe open for writing and O_NONBLOCK is set,
read() shall return -1 and set errno to [EAGAIN].
- If some process has the pipe open for writing and O_NONBLOCK is clear,
read() shall block the calling thread until some data is written or
the pipe is closed by all processes that had the pipe open for writing.
# return value
Returns number of bytes read.
Quoting POSIX:
The value returned may be less than nbyte if:
- the number of bytes left in the file is less than nbyte
- the read() request was interrupted by a signal
- if the file is a pipe or FIFO or special file and has fewer
than nbyte bytes immediately available for reading.
Therefore on a regular file, this is how the end of file can be recognized.
On error return -1 and set errno.
# lseek
Like ANSI C fseek for file descriptors.
lseek cannot be done on certain file descriptor types which are not seekable,
for example on pipes.
# lseek after eof
If data is writen with offset after file size, file size is increased and data skipped reads `(int)0` (`'\0'`).
This contrasts with ANSI C fseek, in which this is undefined behaviour.
# fcntl
Manipulate a file descriptor.
Check if a fd is open: <http://stackoverflow.com/questions/12340695/how-to-check-if-a-given-file-descriptor-stored-in-a-variable-is-still-valid>
# dup
Duplicate file descriptor.
Same as:
fcntl(fildes, F_DUPFD, 0);
# send
Generalization of write:
<http://pubs.opengroup.org/onlinepubs/9699919799/functions/send.html>
TODO
# recv
Generalization of read:
<http://pubs.opengroup.org/onlinepubs/9699919799/functions/recv.html>
TODO
*/
{
int fd;
char in[] = "abcd";
int nbytes = strlen(in);
char *out = malloc (nbytes + 1);
char *fname = TMPFILE("open");
/* BAD forget O_CREAT on non-existent file gives ENOENT */
{
fd = open("/i/do/not/exist", O_RDONLY, S_IRWXU);
if (fd == -1) {
assert(errno == ENOENT);
} else {
assert(false);
}
}
/* BAD write on a O_RDONLY fd gives errno EBADF */
{
int fd;
char *fname = TMPFILE("write_rdonly");
fd = open(fname, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
} else {
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
fd = open(fname, O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
} else {
if (write(fd, "a", 1) == -1) {
assert(errno == EBADF);
} else {
assert(false);
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
}
/*
Open and write without truncate.
Output:
after write 1: abcd
after write 2: 01cd
*/
{
/* Set file to `abc`. */
{
fd = open(fname, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
} else {
if (write(fd, in, nbytes) != nbytes) {
perror("write");
exit(EXIT_FAILURE);
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
}
/* Open and write to it without truncating. */
{
fd = open(fname, O_RDWR);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
} else {
if (write(fd, "01", 2) != 2) {
perror("write");
exit(EXIT_FAILURE);
}
}
}
/* Check the new result. */
{
if (lseek(fd, 0, SEEK_SET) != 0) {
perror("lseek");
exit(EXIT_FAILURE);
}
if (read(fd, out, nbytes) != nbytes) {
perror("read");
exit(EXIT_FAILURE);
} else {
/* The first two bytes were overwriten. */
assert(memcmp(out, "01cd", nbytes) == 0);
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
close(fd);
}
}
/*
`lseek` after EOF
*/
{
int fd;
char out[2];
fd = open(TMPFILE("lseek"), O_RDWR | O_CREAT | O_TRUNC, S_IRWXU);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
} else {
if (lseek(fd, 1, SEEK_SET) != 1) {
perror("lseek");
exit(EXIT_FAILURE);
}
if (write(fd, "a", 1) != 1) {
perror("write");
exit(EXIT_FAILURE);
}
/* Read after eof, return 0 and read nothing. */
if (read(fd, out, 1) != 0) {
assert(false);
}
if (lseek(fd, 0, SEEK_SET) != 0) {
perror("lseek");
exit(EXIT_FAILURE);
}
/* Byte 0 was never writen, so reading it returns `(int)0`. */
if (read(fd, out, 2) != 2) {
perror("read");
exit(EXIT_FAILURE);
} else {
assert(memcmp(out, "\0a", 2) == 0);
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
}
/*
File descriptors open by default to all processes.
Analogous to ANSI C `stdout`, `stdin` and `stderr`, except that the ANSI C `FILE*` objects.
# STDIN_FILENO
stdin
# STDOUT_FILENO
stdout
# STDERR_FILENO
stderr
*/
{
printf("STDIN_FILENO = %d\n", STDIN_FILENO);
printf("STDOUT_FILENO = %d\n", STDOUT_FILENO);
printf("STDERR_FILENO = %d\n", STDERR_FILENO);
}
/*
# aio family
# Asynchronous IO
# aio_cancel
# aio_error
# aio_fsync
# aio_read
# aio_return
# aio_suspend
# aio_write
Great soruce: <http://www.fsl.cs.sunysb.edu/~vass/linux-aio.txt>
In Linux, implemented with the system calls:
io_cancel(2) 2.6
io_destroy(2) 2.6
io_getevents(2) 2.6
io_setup(2) 2.6
io_submit(2) 2.6
*/
{
/* TODO */
}
}
/*
# link
Create hardlink to file.
If newfile exists, the link is not created, returns -1 and sets `errno = EEXIST`
# unlink
Delete file.
Is called unlink because what you are doing is not to directly remove a file from disk
but instead remove one hardlink for the data.
If the number of hardlinks to a data equals 0, it the data gets deleted.
If the given path does not exist `errno = ENOENT`.
*/
{
int fd;
char in[] = "a";
char in_new[] = "b";
int nbytes = strlen(in);
char *out = malloc(nbytes);
char *oldpath = TMPFILE("link_old");
char *newpath = TMPFILE("link_new");
/* Create old. */
fd = open(oldpath, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
} else {
if (write(fd, in, nbytes) != nbytes) {
perror("write");
exit(EXIT_FAILURE);
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
/* Ensure that the new path does not exist */
/* `ENOENT` is ok since the path may not exist */
if (unlink(newpath) == -1 && errno != ENOENT) {
perror("link");
exit(EXIT_FAILURE);
}
/* Make the hardlink. */
if (link(oldpath, newpath) == -1) {
perror("link");
exit(EXIT_FAILURE);
}
/* Write to new. */
fd = open(newpath, O_WRONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
} else {
if (write(fd, in_new, nbytes) != nbytes) {
perror("write");
exit(EXIT_FAILURE);
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
/* assert that it reflected on old */
fd = open(oldpath, O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
} else {
if (read(fd, out, nbytes) != nbytes) {
perror("read");
exit(EXIT_FAILURE);
}
assert(memcmp(out, in_new, nbytes) == 0);
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
free(out);
}
/* # Pathname operations */
{
/*
# realpath
Return:
- absolute path
- cannonical: does not contain `.` nor `..`.
Interface:
char *realpath(const char *restrict file_name,
char *restrict resolved_name);
The function does completelly different things depending if resolved_name is NULL or not:
- `resolved_name == NULL`: realpath mallocs the path for you and returns it.
You have to free it in the future.
This is a good options if you don't already have a buffer of the right size, since calculating the required buffer size
would be annoying (would require calling `pathconf`).
- `resolved_name == NULL`: the pathname is copied to `resolved_name`.
You must make sure that you have enough space there.
This is a good option if you already have a large enough buffer laying around,
since it does not require dynamic allocation.
Of course, ensuring that your buffer is large enough means doing messy `pathconfs` at some point.
*/
{
char *rp = realpath(".", NULL);
if (rp) {
printf("realpath(\".\") = %s\n", rp);
} else {
perror("realpath");
exit(EXIT_FAILURE);
}
free(rp);
}
/*
# dirname # basename
p may be modified memory is statically allocated
and may change on next dirname/basename call.
TODO what is p
behaviour:
path dirname basename
---------- -------- ---------
"/usr/lib" "/usr" "lib"
"/usr/" "/" "usr"
"usr" "." "usr"
"/" "/" "/"
"." "." "."
".." "." ".."
*/
{
char p[1024];
char* res;
strcpy(p, "a/b");
res = dirname(p);
assert(strcmp(res, "a") == 0);
strcpy(p, "a/b");
res = basename(p);
assert(strcmp(res, "b") == 0);
}
}
/*
# getrlimit
Returns the maximum value for a given resource.
Linux has a system call with that name.
There are two types of limits:
- soft: can be increased by any process to any value lower than the hard maximum
- hard: only processes with special privileges may increase the hard limit
If a resource goes over the soft limit, the kernel may choose to kill the process
Interfaces:
int getrlimit(int resource, struct rlimit *rlp);
int setrlimit(int resource, const struct rlimit *rlp);
- resource: see the docs for a description of each possible value
- rlp: struct of type:
struct rlimit {
rlim_t rlim_cur // The current (soft) limit.
rlim_t rlim_max // The hard limit.
}
where `rlim_t` is an unsigned integer
*/
{
struct rlimit limit;
if (getrlimit(RLIMIT_DATA, &limit) == -1) {
perror("getrlimit(RLIMIT_DATA, ...) failed");
exit(EXIT_FAILURE);
} else {
/* maximum process memory in bytes */
if (limit.rlim_max == RLIM_INFINITY) {
/* RLIM_INFINITY means that no limit is imposed on the resource */
puts("RLIMIT_DATA: no limit imposed");
} else {
printf(
"RLIMIT_DATA\n soft = %ju\n hard = %ju\n",
(uintmax_t)limit.rlim_cur,
(uintmax_t)limit.rlim_max
);
}
}
/* OK, enough of error checking from now on. */
printf("RLIM_INFINITY = %ju\n", (uintmax_t)RLIM_INFINITY);
/* maximum total CPU usage in seconds. */
getrlimit(RLIMIT_CPU, &limit);
printf(
"RLIMIT_CPU\n soft = %ju\n hard = %ju\n",
(uintmax_t)limit.rlim_cur,
(uintmax_t)limit.rlim_max
);
/* Maximum file size in bytes. */
getrlimit(RLIMIT_FSIZE, &limit);
printf(
"RLIMIT_FSIZE\n soft = %ju\n hard = %ju\n",
(uintmax_t)limit.rlim_cur,
(uintmax_t)limit.rlim_max
);
/* Number of file descriptors: */
getrlimit(RLIMIT_NOFILE, &limit);
printf(
"RLIMIT_NOFILE\n soft = %ju\n hard = %ju\n",
(uintmax_t)limit.rlim_cur,
(uintmax_t)limit.rlim_max
);
}
/*
# limits.h
This header exists in ANSI C, and POSIX extends it with several values.
Defines current and possible maximums and minimums for several resources.
Some resources cannot cannot be evaluated statically.
For example the maximum path length depends on which directory we are talking about,
since different directories can be on different mount points.
In those cases, limits defines a KEY value which can be passed to a function that gets
the actual values for a given key, for example pathconf or sysconf.
For resources that have fixed values, this header furnishes them directly.
*/
{
/* Static macros. */
{
/* TODO what is it */
printf("NL_ARGMAX = %d\n", NL_ARGMAX);
/* Maximum value that fits into a `size_t`. */
printf("SSIZE_MAX (Mib) = %ju\n", (uintmax_t)SSIZE_MAX / (1 << 20));
}
/*
# maximum path length
This is needed often when you need to deal with paths names.
Sources:
- <http://stackoverflow.com/questions/2285750/size-of-posix-path-max>
Keep in mind that this value can vary even while a program is running,
and depends of the underlying filesystem, and therefore of the direcotory you are in.
As a consequence of this, it does not make sense to have a macro constant and use it to create
fixed variable arrays: a function is needed, and memory must be allocated with malloc.
# pathconf
Similar to sysconf, but for parameters that depend on a path, such as maxium filename lengths.
*/
{
/* Max basename in given dir including trailling null: */
printf("pathconf(\".\", _PC_NAME_MAX) = %ld\n", pathconf(".", _PC_NAME_MAX));
/* Max pathname in (TODO this is per device?) */
printf("pathconf(\".\", _PC_PATH_MAX) = %ld\n", pathconf(".", _PC_PATH_MAX));
}
}