-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathsort.c
4544 lines (3954 loc) · 134 KB
/
sort.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
/* sort - sort lines of text (with all kinds of options).
Copyright (C) 1988, 1991-2010 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written December 1988 by Mike Haertel.
The author may be reached (Email) at the address [email protected],
or (US mail) as Mike Haertel c/o Free Software Foundation.
Ørn E. Hansen added NLS support in 1997. */
#include <config.h>
#include <getopt.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include "system.h"
#include "argmatch.h"
#include "error.h"
#include "fadvise.h"
#include "filevercmp.h"
#include "hard-locale.h"
#include "hash.h"
#include "heap.h"
#include "ignore-value.h"
#include "md5.h"
#include "mbswidth.h"
#include "nproc.h"
#include "physmem.h"
#include "posixver.h"
#include "quote.h"
#include "quotearg.h"
#include "randread.h"
#include "readtokens0.h"
#include "stdio--.h"
#include "stdlib--.h"
#include "strnumcmp.h"
#include "xmemcoll.h"
#include "xnanosleep.h"
#include "xstrtol.h"
#if HAVE_SYS_RESOURCE_H
# include <sys/resource.h>
#endif
#ifndef RLIMIT_DATA
struct rlimit { size_t rlim_cur; };
# define getrlimit(Resource, Rlp) (-1)
#endif
/* The official name of this program (e.g., no `g' prefix). */
#define PROGRAM_NAME "sort"
#define AUTHORS \
proper_name ("Mike Haertel"), \
proper_name ("Paul Eggert")
#if HAVE_LANGINFO_CODESET
# include <langinfo.h>
#endif
/* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
present. */
#ifndef SA_NOCLDSTOP
# define SA_NOCLDSTOP 0
/* No sigprocmask. Always 'return' zero. */
# define sigprocmask(How, Set, Oset) (0)
# define sigset_t int
# if ! HAVE_SIGINTERRUPT
# define siginterrupt(sig, flag) /* empty */
# endif
#endif
#if !defined OPEN_MAX && defined NR_OPEN
# define OPEN_MAX NR_OPEN
#endif
#if !defined OPEN_MAX
# define OPEN_MAX 20
#endif
#define UCHAR_LIM (UCHAR_MAX + 1)
#if HAVE_C99_STRTOLD
# define long_double long double
#else
# define long_double double
# undef strtold
# define strtold strtod
#endif
#ifndef DEFAULT_TMPDIR
# define DEFAULT_TMPDIR "/tmp"
#endif
/* Maximum number of lines to merge every time a NODE is taken from
the MERGE_QUEUE. Node is at LEVEL in the binary merge tree,
and is responsible for merging TOTAL lines. */
#define MAX_MERGE(total, level) ((total) / ((2 << level) * (2 << level)) + 1)
/* Heuristic value for the number of lines for which it is worth
creating a subthread, during an internal merge sort, on a machine
that has processors galore. Currently this number is just a guess.
This value must be at least 4. We don't know of any machine where
this number has any practical effect. */
enum { SUBTHREAD_LINES_HEURISTIC = 4 };
/* Exit statuses. */
enum
{
/* POSIX says to exit with status 1 if invoked with -c and the
input is not properly sorted. */
SORT_OUT_OF_ORDER = 1,
/* POSIX says any other irregular exit must exit with a status
code greater than 1. */
SORT_FAILURE = 2
};
enum
{
/* The number of times we should try to fork a compression process
(we retry if the fork call fails). We don't _need_ to compress
temp files, this is just to reduce disk access, so this number
can be small. Each retry doubles in duration. */
MAX_FORK_TRIES_COMPRESS = 4,
/* The number of times we should try to fork a decompression process.
If we can't fork a decompression process, we can't sort, so this
number should be big. Each retry doubles in duration. */
MAX_FORK_TRIES_DECOMPRESS = 9
};
enum
{
/* Level of the end-of-merge node, one level above the root. */
MERGE_END = 0,
/* Level of the root node in merge tree. */
MERGE_ROOT = 1
};
/* The representation of the decimal point in the current locale. */
static int decimal_point;
/* Thousands separator; if -1, then there isn't one. */
static int thousands_sep;
/* Nonzero if the corresponding locales are hard. */
static bool hard_LC_COLLATE;
#if HAVE_NL_LANGINFO
static bool hard_LC_TIME;
#endif
#define NONZERO(x) ((x) != 0)
/* The kind of blanks for '-b' to skip in various options. */
enum blanktype { bl_start, bl_end, bl_both };
/* The character marking end of line. Default to \n. */
static char eolchar = '\n';
/* Lines are held in core as counted strings. */
struct line
{
char *text; /* Text of the line. */
size_t length; /* Length including final newline. */
char *keybeg; /* Start of first key. */
char *keylim; /* Limit of first key. */
};
/* Input buffers. */
struct buffer
{
char *buf; /* Dynamically allocated buffer,
partitioned into 3 regions:
- input data;
- unused area;
- an array of lines, in reverse order. */
size_t used; /* Number of bytes used for input data. */
size_t nlines; /* Number of lines in the line array. */
size_t alloc; /* Number of bytes allocated. */
size_t left; /* Number of bytes left from previous reads. */
size_t line_bytes; /* Number of bytes to reserve for each line. */
bool eof; /* An EOF has been read. */
};
struct keyfield
{
size_t sword; /* Zero-origin 'word' to start at. */
size_t schar; /* Additional characters to skip. */
size_t eword; /* Zero-origin last 'word' of key. */
size_t echar; /* Additional characters in field. */
bool const *ignore; /* Boolean array of characters to ignore. */
char const *translate; /* Translation applied to characters. */
bool skipsblanks; /* Skip leading blanks when finding start. */
bool skipeblanks; /* Skip leading blanks when finding end. */
bool numeric; /* Flag for numeric comparison. Handle
strings of digits with optional decimal
point, but no exponential notation. */
bool random; /* Sort by random hash of key. */
bool general_numeric; /* Flag for general, numeric comparison.
Handle numbers in exponential notation. */
bool human_numeric; /* Flag for sorting by human readable
units with either SI xor IEC prefixes. */
bool month; /* Flag for comparison by month name. */
bool reverse; /* Reverse the sense of comparison. */
bool version; /* sort by version number */
bool obsolete_used; /* obsolescent key option format is used. */
struct keyfield *next; /* Next keyfield to try. */
};
struct month
{
char const *name;
int val;
};
/* Binary merge tree node. */
struct merge_node
{
struct line *lo; /* Lines to merge from LO child node. */
struct line *hi; /* Lines to merge from HI child ndoe. */
struct line *end_lo; /* End of available lines from LO. */
struct line *end_hi; /* End of available lines from HI. */
struct line **dest; /* Pointer to destination of merge. */
size_t nlo; /* Total Lines remaining from LO. */
size_t nhi; /* Total lines remaining from HI. */
size_t level; /* Level in merge tree. */
struct merge_node *parent; /* Parent node. */
bool queued; /* Node is already in heap. */
pthread_spinlock_t *lock; /* Lock for node operations. */
};
/* Priority queue of merge nodes. */
struct merge_node_queue
{
struct heap *priority_queue; /* Priority queue of merge tree nodes. */
pthread_mutex_t mutex; /* Lock for queue operations. */
pthread_cond_t cond; /* Conditional wait for empty queue to populate
when popping. */
};
/* FIXME: None of these tables work with multibyte character sets.
Also, there are many other bugs when handling multibyte characters.
One way to fix this is to rewrite `sort' to use wide characters
internally, but doing this with good performance is a bit
tricky. */
/* Table of blanks. */
static bool blanks[UCHAR_LIM];
/* Table of non-printing characters. */
static bool nonprinting[UCHAR_LIM];
/* Table of non-dictionary characters (not letters, digits, or blanks). */
static bool nondictionary[UCHAR_LIM];
/* Translation table folding lower case to upper. */
static char fold_toupper[UCHAR_LIM];
#define MONTHS_PER_YEAR 12
/* Table mapping month names to integers.
Alphabetic order allows binary search. */
static struct month monthtab[] =
{
{"APR", 4},
{"AUG", 8},
{"DEC", 12},
{"FEB", 2},
{"JAN", 1},
{"JUL", 7},
{"JUN", 6},
{"MAR", 3},
{"MAY", 5},
{"NOV", 11},
{"OCT", 10},
{"SEP", 9}
};
/* During the merge phase, the number of files to merge at once. */
#define NMERGE_DEFAULT 16
/* Minimum size for a merge or check buffer. */
#define MIN_MERGE_BUFFER_SIZE (2 + sizeof (struct line))
/* Minimum sort size; the code might not work with smaller sizes. */
#define MIN_SORT_SIZE (nmerge * MIN_MERGE_BUFFER_SIZE)
/* The number of bytes needed for a merge or check buffer, which can
function relatively efficiently even if it holds only one line. If
a longer line is seen, this value is increased. */
static size_t merge_buffer_size = MAX (MIN_MERGE_BUFFER_SIZE, 256 * 1024);
/* The approximate maximum number of bytes of main memory to use, as
specified by the user. Zero if the user has not specified a size. */
static size_t sort_size;
/* The guessed size for non-regular files. */
#define INPUT_FILE_SIZE_GUESS (1024 * 1024)
/* Array of directory names in which any temporary files are to be created. */
static char const **temp_dirs;
/* Number of temporary directory names used. */
static size_t temp_dir_count;
/* Number of allocated slots in temp_dirs. */
static size_t temp_dir_alloc;
/* Flag to reverse the order of all comparisons. */
static bool reverse;
/* Flag for stable sort. This turns off the last ditch bytewise
comparison of lines, and instead leaves lines in the same order
they were read if all keys compare equal. */
static bool stable;
/* If TAB has this value, blanks separate fields. */
enum { TAB_DEFAULT = CHAR_MAX + 1 };
/* Tab character separating fields. If TAB_DEFAULT, then fields are
separated by the empty string between a non-blank character and a blank
character. */
static int tab = TAB_DEFAULT;
/* Flag to remove consecutive duplicate lines from the output.
Only the last of a sequence of equal lines will be output. */
static bool unique;
/* Nonzero if any of the input files are the standard input. */
static bool have_read_stdin;
/* List of key field comparisons to be tried. */
static struct keyfield *keylist;
/* Program used to (de)compress temp files. Must accept -d. */
static char const *compress_program;
/* Annotate the output with extra info to aid the user. */
static bool debug;
/* Maximum number of files to merge in one go. If more than this
number are present, temp files will be used. */
static unsigned int nmerge = NMERGE_DEFAULT;
/* Report MESSAGE for FILE, then clean up and exit.
If FILE is null, it represents standard output. */
static void die (char const *, char const *) ATTRIBUTE_NORETURN;
static void
die (char const *message, char const *file)
{
error (0, errno, "%s: %s", message, file ? file : _("standard output"));
exit (SORT_FAILURE);
}
void
usage (int status)
{
if (status != EXIT_SUCCESS)
fprintf (stderr, _("Try `%s --help' for more information.\n"),
program_name);
else
{
printf (_("\
Usage: %s [OPTION]... [FILE]...\n\
or: %s [OPTION]... --files0-from=F\n\
"),
program_name, program_name);
fputs (_("\
Write sorted concatenation of all FILE(s) to standard output.\n\
\n\
"), stdout);
fputs (_("\
Mandatory arguments to long options are mandatory for short options too.\n\
"), stdout);
fputs (_("\
Ordering options:\n\
\n\
"), stdout);
fputs (_("\
-b, --ignore-leading-blanks ignore leading blanks\n\
-d, --dictionary-order consider only blanks and alphanumeric characters\n\
-f, --ignore-case fold lower case to upper case characters\n\
"), stdout);
fputs (_("\
-g, --general-numeric-sort compare according to general numerical value\n\
-i, --ignore-nonprinting consider only printable characters\n\
-M, --month-sort compare (unknown) < `JAN' < ... < `DEC'\n\
"), stdout);
fputs (_("\
-h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G)\n\
"), stdout);
fputs (_("\
-n, --numeric-sort compare according to string numerical value\n\
-R, --random-sort sort by random hash of keys\n\
--random-source=FILE get random bytes from FILE\n\
-r, --reverse reverse the result of comparisons\n\
"), stdout);
fputs (_("\
--sort=WORD sort according to WORD:\n\
general-numeric -g, human-numeric -h, month -M,\n\
numeric -n, random -R, version -V\n\
-V, --version-sort natural sort of (version) numbers within text\n\
\n\
"), stdout);
fputs (_("\
Other options:\n\
\n\
"), stdout);
fputs (_("\
--batch-size=NMERGE merge at most NMERGE inputs at once;\n\
for more use temp files\n\
"), stdout);
fputs (_("\
-c, --check, --check=diagnose-first check for sorted input; do not sort\n\
-C, --check=quiet, --check=silent like -c, but do not report first bad line\n\
--compress-program=PROG compress temporaries with PROG;\n\
decompress them with PROG -d\n\
"), stdout);
fputs (_("\
--debug annotate the part of the line used to sort,\n\
and warn about questionable usage to stderr\n\
--files0-from=F read input from the files specified by\n\
NUL-terminated names in file F;\n\
If F is - then read names from standard input\n\
"), stdout);
fputs (_("\
-k, --key=POS1[,POS2] start a key at POS1 (origin 1), end it at POS2\n\
(default end of line). See POS syntax below\n\
-m, --merge merge already sorted files; do not sort\n\
"), stdout);
fputs (_("\
-o, --output=FILE write result to FILE instead of standard output\n\
-s, --stable stabilize sort by disabling last-resort comparison\n\
-S, --buffer-size=SIZE use SIZE for main memory buffer\n\
"), stdout);
printf (_("\
-t, --field-separator=SEP use SEP instead of non-blank to blank transition\n\
-T, --temporary-directory=DIR use DIR for temporaries, not $TMPDIR or %s;\n\
multiple options specify multiple directories\n\
--parallel=N limit the number of sorts run concurrently to N\n\
-u, --unique with -c, check for strict ordering;\n\
without -c, output only the first of an equal run\n\
"), DEFAULT_TMPDIR);
fputs (_("\
-z, --zero-terminated end lines with 0 byte, not newline\n\
"), stdout);
fputs (HELP_OPTION_DESCRIPTION, stdout);
fputs (VERSION_OPTION_DESCRIPTION, stdout);
fputs (_("\
\n\
POS is F[.C][OPTS], where F is the field number and C the character position\n\
in the field; both are origin 1. If neither -t nor -b is in effect, characters\n\
in a field are counted from the beginning of the preceding whitespace. OPTS is\n\
one or more single-letter ordering options, which override global ordering\n\
options for that key. If no key is given, use the entire line as the key.\n\
\n\
SIZE may be followed by the following multiplicative suffixes:\n\
"), stdout);
fputs (_("\
% 1% of memory, b 1, K 1024 (default), and so on for M, G, T, P, E, Z, Y.\n\
\n\
With no FILE, or when FILE is -, read standard input.\n\
\n\
*** WARNING ***\n\
The locale specified by the environment affects sort order.\n\
Set LC_ALL=C to get the traditional sort order that uses\n\
native byte values.\n\
"), stdout );
emit_ancillary_info ();
}
exit (status);
}
/* For long options that have no equivalent short option, use a
non-character as a pseudo short option, starting with CHAR_MAX + 1. */
enum
{
CHECK_OPTION = CHAR_MAX + 1,
COMPRESS_PROGRAM_OPTION,
DEBUG_PROGRAM_OPTION,
FILES0_FROM_OPTION,
NMERGE_OPTION,
RANDOM_SOURCE_OPTION,
SORT_OPTION,
PARALLEL_OPTION
};
static char const short_options[] = "-bcCdfghik:mMno:rRsS:t:T:uVy:z";
static struct option const long_options[] =
{
{"ignore-leading-blanks", no_argument, NULL, 'b'},
{"check", optional_argument, NULL, CHECK_OPTION},
{"compress-program", required_argument, NULL, COMPRESS_PROGRAM_OPTION},
{"debug", no_argument, NULL, DEBUG_PROGRAM_OPTION},
{"dictionary-order", no_argument, NULL, 'd'},
{"ignore-case", no_argument, NULL, 'f'},
{"files0-from", required_argument, NULL, FILES0_FROM_OPTION},
{"general-numeric-sort", no_argument, NULL, 'g'},
{"ignore-nonprinting", no_argument, NULL, 'i'},
{"key", required_argument, NULL, 'k'},
{"merge", no_argument, NULL, 'm'},
{"month-sort", no_argument, NULL, 'M'},
{"numeric-sort", no_argument, NULL, 'n'},
{"human-numeric-sort", no_argument, NULL, 'h'},
{"version-sort", no_argument, NULL, 'V'},
{"random-sort", no_argument, NULL, 'R'},
{"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},
{"sort", required_argument, NULL, SORT_OPTION},
{"output", required_argument, NULL, 'o'},
{"reverse", no_argument, NULL, 'r'},
{"stable", no_argument, NULL, 's'},
{"batch-size", required_argument, NULL, NMERGE_OPTION},
{"buffer-size", required_argument, NULL, 'S'},
{"field-separator", required_argument, NULL, 't'},
{"temporary-directory", required_argument, NULL, 'T'},
{"unique", no_argument, NULL, 'u'},
{"zero-terminated", no_argument, NULL, 'z'},
{"parallel", required_argument, NULL, PARALLEL_OPTION},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0},
};
#define CHECK_TABLE \
_ct_("quiet", 'C') \
_ct_("silent", 'C') \
_ct_("diagnose-first", 'c')
static char const *const check_args[] =
{
#define _ct_(_s, _c) _s,
CHECK_TABLE NULL
#undef _ct_
};
static char const check_types[] =
{
#define _ct_(_s, _c) _c,
CHECK_TABLE
#undef _ct_
};
#define SORT_TABLE \
_st_("general-numeric", 'g') \
_st_("human-numeric", 'h') \
_st_("month", 'M') \
_st_("numeric", 'n') \
_st_("random", 'R') \
_st_("version", 'V')
static char const *const sort_args[] =
{
#define _st_(_s, _c) _s,
SORT_TABLE NULL
#undef _st_
};
static char const sort_types[] =
{
#define _st_(_s, _c) _c,
SORT_TABLE
#undef _st_
};
/* The set of signals that are caught. */
static sigset_t caught_signals;
/* Critical section status. */
struct cs_status
{
bool valid;
sigset_t sigs;
};
/* Enter a critical section. */
static struct cs_status
cs_enter (void)
{
struct cs_status status;
status.valid = (sigprocmask (SIG_BLOCK, &caught_signals, &status.sigs) == 0);
return status;
}
/* Leave a critical section. */
static void
cs_leave (struct cs_status status)
{
if (status.valid)
{
/* Ignore failure when restoring the signal mask. */
sigprocmask (SIG_SETMASK, &status.sigs, NULL);
}
}
/* The list of temporary files. */
struct tempnode
{
struct tempnode *volatile next;
pid_t pid; /* If compressed, the pid of compressor, else zero */
char name[1]; /* Actual size is 1 + file name length. */
};
static struct tempnode *volatile temphead;
static struct tempnode *volatile *temptail = &temphead;
struct sortfile
{
char const *name;
pid_t pid; /* If compressed, the pid of compressor, else zero */
};
/* A table where we store compression process states. We clean up all
processes in a timely manner so as not to exhaust system resources,
so we store the info on whether the process is still running, or has
been reaped here. */
static Hash_table *proctab;
enum { INIT_PROCTAB_SIZE = 47 };
enum procstate { ALIVE, ZOMBIE };
/* A proctab entry. The COUNT field is there in case we fork a new
compression process that has the same PID as an old zombie process
that is still in the table (because the process to decompress the
temp file it was associated with hasn't started yet). */
struct procnode
{
pid_t pid;
enum procstate state;
size_t count;
};
static size_t
proctab_hasher (void const *entry, size_t tabsize)
{
struct procnode const *node = entry;
return node->pid % tabsize;
}
static bool
proctab_comparator (void const *e1, void const *e2)
{
struct procnode const *n1 = e1, *n2 = e2;
return n1->pid == n2->pid;
}
/* The total number of forked processes (compressors and decompressors)
that have not been reaped yet. */
static size_t nprocs;
/* The number of child processes we'll allow before we try to reap some. */
enum { MAX_PROCS_BEFORE_REAP = 2 };
/* If 0 < PID, wait for the child process with that PID to exit.
If PID is -1, clean up a random child process which has finished and
return the process ID of that child. If PID is -1 and no processes
have quit yet, return 0 without waiting. */
static pid_t
reap (pid_t pid)
{
int status;
pid_t cpid = waitpid (pid, &status, pid < 0 ? WNOHANG : 0);
if (cpid < 0)
error (SORT_FAILURE, errno, _("waiting for %s [-d]"),
compress_program);
else if (0 < cpid)
{
if (! WIFEXITED (status) || WEXITSTATUS (status))
error (SORT_FAILURE, 0, _("%s [-d] terminated abnormally"),
compress_program);
--nprocs;
}
return cpid;
}
/* Add the PID of a running compression process to proctab, or update
the entry COUNT and STATE fields if it's already there. This also
creates the table for us the first time it's called. */
static void
register_proc (pid_t pid)
{
struct procnode test, *node;
if (! proctab)
{
proctab = hash_initialize (INIT_PROCTAB_SIZE, NULL,
proctab_hasher,
proctab_comparator,
free);
if (! proctab)
xalloc_die ();
}
test.pid = pid;
node = hash_lookup (proctab, &test);
if (node)
{
node->state = ALIVE;
++node->count;
}
else
{
node = xmalloc (sizeof *node);
node->pid = pid;
node->state = ALIVE;
node->count = 1;
if (hash_insert (proctab, node) == NULL)
xalloc_die ();
}
}
/* This is called when we reap a random process. We don't know
whether we have reaped a compression process or a decompression
process until we look in the table. If there's an ALIVE entry for
it, then we have reaped a compression process, so change the state
to ZOMBIE. Otherwise, it's a decompression processes, so ignore it. */
static void
update_proc (pid_t pid)
{
struct procnode test, *node;
test.pid = pid;
node = hash_lookup (proctab, &test);
if (node)
node->state = ZOMBIE;
}
/* This is for when we need to wait for a compression process to exit.
If it has a ZOMBIE entry in the table then it's already dead and has
been reaped. Note that if there's an ALIVE entry for it, it still may
already have died and been reaped if a second process was created with
the same PID. This is probably exceedingly rare, but to be on the safe
side we will have to wait for any compression process with this PID. */
static void
wait_proc (pid_t pid)
{
struct procnode test, *node;
test.pid = pid;
node = hash_lookup (proctab, &test);
if (node->state == ALIVE)
reap (pid);
node->state = ZOMBIE;
if (! --node->count)
{
hash_delete (proctab, node);
free (node);
}
}
/* Keep reaping finished children as long as there are more to reap.
This doesn't block waiting for any of them, it only reaps those
that are already dead. */
static void
reap_some (void)
{
pid_t pid;
while (0 < nprocs && (pid = reap (-1)))
update_proc (pid);
}
/* Clean up any remaining temporary files. */
static void
cleanup (void)
{
struct tempnode const *node;
for (node = temphead; node; node = node->next)
unlink (node->name);
temphead = NULL;
}
/* Cleanup actions to take when exiting. */
static void
exit_cleanup (void)
{
if (temphead)
{
/* Clean up any remaining temporary files in a critical section so
that a signal handler does not try to clean them too. */
struct cs_status cs = cs_enter ();
cleanup ();
cs_leave (cs);
}
close_stdout ();
}
/* Create a new temporary file, returning its newly allocated tempnode.
Store into *PFD the file descriptor open for writing.
If the creation fails, return NULL and store -1 into *PFD if the
failure is due to file descriptor exhaustion and
SURVIVE_FD_EXHAUSTION; otherwise, die. */
static struct tempnode *
create_temp_file (int *pfd, bool survive_fd_exhaustion)
{
static char const slashbase[] = "/sortXXXXXX";
static size_t temp_dir_index;
int fd;
int saved_errno;
char const *temp_dir = temp_dirs[temp_dir_index];
size_t len = strlen (temp_dir);
struct tempnode *node =
xmalloc (offsetof (struct tempnode, name) + len + sizeof slashbase);
char *file = node->name;
struct cs_status cs;
memcpy (file, temp_dir, len);
memcpy (file + len, slashbase, sizeof slashbase);
node->next = NULL;
node->pid = 0;
if (++temp_dir_index == temp_dir_count)
temp_dir_index = 0;
/* Create the temporary file in a critical section, to avoid races. */
cs = cs_enter ();
fd = mkstemp (file);
if (0 <= fd)
{
*temptail = node;
temptail = &node->next;
}
saved_errno = errno;
cs_leave (cs);
errno = saved_errno;
if (fd < 0)
{
if (! (survive_fd_exhaustion && errno == EMFILE))
error (SORT_FAILURE, errno, _("cannot create temporary file in %s"),
quote (temp_dir));
free (node);
node = NULL;
}
*pfd = fd;
return node;
}
/* Return a stream for FILE, opened with mode HOW. A null FILE means
standard output; HOW should be "w". When opening for input, "-"
means standard input. To avoid confusion, do not return file
descriptors STDIN_FILENO, STDOUT_FILENO, or STDERR_FILENO when
opening an ordinary FILE. Return NULL if unsuccessful.
fadvise() is used to specify an access pattern for input files.
There are a few hints we could possibly provide,
and after careful testing it was decided that
specifying POSIX_FADV_SEQUENTIAL was not detrimental
to any cases. On Linux 2.6.31, this option doubles
the size of read ahead performed and thus was seen to
benefit these cases:
Merging
Sorting with a smaller internal buffer
Reading from faster flash devices
In _addition_ one could also specify other hints...
POSIX_FADV_WILLNEED was tested, but Linux 2.6.31
at least uses that to _synchronously_ prepopulate the cache
with the specified range. While sort does need to
read all of its input before outputting, a synchronous
read of the whole file up front precludes any processing
that sort could do in parallel with the system doing
read ahead of the data. This was seen to have negative effects
in a couple of cases:
Merging
Sorting with a smaller internal buffer
Note this option was seen to shorten the runtime for sort
on a multicore system with lots of RAM and other processes
competing for CPU. It could be argued that more explicit
scheduling hints with `nice` et. al. are more appropriate
for this situation.
POSIX_FADV_NOREUSE is a possibility as it could lower
the priority of input data in the cache as sort will
only need to process it once. However its functionality
has changed over Linux kernel versions and as of 2.6.31
it does nothing and thus we can't depend on what it might
do in future.
POSIX_FADV_DONTNEED is not appropriate for user specified
input files, but for temp files we do want to drop the
cache immediately after processing. This is done implicitly
however when the files are unlinked. */
static FILE *
stream_open (char const *file, char const *how)
{
if (!file)
return stdout;
if (*how == 'r')
{
FILE *fp;
if (STREQ (file, "-"))
{
have_read_stdin = true;
fp = stdin;
}
else
fp = fopen (file, how);
fadvise (fp, FADVISE_SEQUENTIAL);
return fp;
}
return fopen (file, how);
}
/* Same as stream_open, except always return a non-null value; die on
failure. */
static FILE *
xfopen (char const *file, char const *how)
{
FILE *fp = stream_open (file, how);
if (!fp)
die (_("open failed"), file);
return fp;
}
/* Close FP, whose name is FILE, and report any errors. */
static void
xfclose (FILE *fp, char const *file)
{
switch (fileno (fp))
{
case STDIN_FILENO:
/* Allow reading stdin from tty more than once. */
if (feof (fp))
clearerr (fp);
break;
case STDOUT_FILENO:
/* Don't close stdout just yet. close_stdout does that. */
if (fflush (fp) != 0)
die (_("fflush failed"), file);
break;
default:
if (fclose (fp) != 0)
die (_("close failed"), file);
break;
}
}
static void
dup2_or_die (int oldfd, int newfd)
{
if (dup2 (oldfd, newfd) < 0)
error (SORT_FAILURE, errno, _("dup2 failed"));
}
/* Fork a child process for piping to and do common cleanup. The
TRIES parameter tells us how many times to try to fork before
giving up. Return the PID of the child, or -1 (setting errno)
on failure. */
static pid_t
pipe_fork (int pipefds[2], size_t tries)
{
#if HAVE_WORKING_FORK
struct tempnode *saved_temphead;
int saved_errno;
double wait_retry = 0.25;
pid_t pid IF_LINT ( = -1);
struct cs_status cs;
if (pipe (pipefds) < 0)
return -1;
while (tries--)
{
/* This is so the child process won't delete our temp files
if it receives a signal before exec-ing. */