sort.c revision 1.35 1 /* $NetBSD: sort.c,v 1.35 2004/02/15 14:22:55 jdolecek Exp $ */
2
3 /*-
4 * Copyright (c) 2000-2003 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Ben Harris and Jaromir Dolecek.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 /*-
40 * Copyright (c) 1993
41 * The Regents of the University of California. All rights reserved.
42 *
43 * This code is derived from software contributed to Berkeley by
44 * Peter McIlroy.
45 *
46 * Redistribution and use in source and binary forms, with or without
47 * modification, are permitted provided that the following conditions
48 * are met:
49 * 1. Redistributions of source code must retain the above copyright
50 * notice, this list of conditions and the following disclaimer.
51 * 2. Redistributions in binary form must reproduce the above copyright
52 * notice, this list of conditions and the following disclaimer in the
53 * documentation and/or other materials provided with the distribution.
54 * 3. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
57 *
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
69 */
70
71 /* Sort sorts a file using an optional user-defined key.
72 * Sort uses radix sort for internal sorting, and allows
73 * a choice of merge sort and radix sort for external sorting.
74 */
75
76 #include "sort.h"
77 #include "fsort.h"
78 #include "pathnames.h"
79
80 #ifndef lint
81 __COPYRIGHT("@(#) Copyright (c) 1993\n\
82 The Regents of the University of California. All rights reserved.\n");
83 #endif /* not lint */
84
85 #ifndef lint
86 __RCSID("$NetBSD: sort.c,v 1.35 2004/02/15 14:22:55 jdolecek Exp $");
87 __SCCSID("@(#)sort.c 8.1 (Berkeley) 6/6/93");
88 #endif /* not lint */
89
90 #include <sys/types.h>
91 #include <sys/time.h>
92 #include <sys/resource.h>
93
94 #include <paths.h>
95 #include <signal.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <unistd.h>
99 #include <locale.h>
100
101 int REC_D = '\n';
102 u_char d_mask[NBINS]; /* flags for rec_d, field_d, <blank> */
103
104 /*
105 * weight tables. Gweights is one of ascii, Rascii..
106 * modified to weight rec_d = 0 (or 255)
107 */
108 u_char ascii[NBINS], Rascii[NBINS], RFtable[NBINS], Ftable[NBINS];
109 int SINGL_FLD = 0, SEP_FLAG = 0, UNIQUE = 0;
110
111 /*
112 * Default to stable sort.
113 */
114 int stable_sort = 1;
115
116 static char toutpath[MAXPATHLEN];
117
118 const char *tmpdir; /* where temporary files should be put */
119
120 static void cleanup __P((void));
121 static void onsignal __P((int));
122 static void usage __P((const char *));
123
124 int main __P((int argc, char **argv));
125
126 int
127 main(argc, argv)
128 int argc;
129 char *argv[];
130 {
131 get_func_t get;
132 int ch, i, stdinflag = 0, tmp = 0;
133 char cflag = 0, mflag = 0;
134 char *outfile, *outpath = 0;
135 struct field *fldtab, *ftpos;
136 size_t fldtab_sz = 2;
137 struct filelist filelist;
138 FILE *outfp = NULL;
139 struct rlimit rl;
140
141 setlocale(LC_ALL, "");
142
143 /* bump RLIMIT_NOFILE to maximum our hard limit allows */
144 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
145 err(2, "getrlimit");
146 rl.rlim_cur = rl.rlim_max;
147 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
148 err(2, "setrlimit");
149
150 d_mask[REC_D = '\n'] = REC_D_F;
151 SINGL_FLD = SEP_FLAG = 0;
152 d_mask['\t'] = d_mask[' '] = BLANK | FLD_D;
153
154 fldtab = malloc(fldtab_sz*sizeof(*fldtab));
155 ftpos = fldtab;
156
157 fixit(&argc, argv);
158
159 if (!(tmpdir = getenv("TMPDIR")))
160 tmpdir = _PATH_TMP;
161
162 while ((ch = getopt(argc, argv, "bcdfik:mHno:rR:sSt:T:ux")) != -1) {
163 switch (ch) {
164 case 'b':
165 fldtab->flags |= BI | BT;
166 break;
167 case 'c':
168 cflag = 1;
169 break;
170 case 'd': case 'f': case 'i': case 'n': case 'r':
171 tmp |= optval(ch, 0);
172 if ((tmp & R) && (tmp & F))
173 fldtab->weights = RFtable;
174 else if (tmp & F)
175 fldtab->weights = Ftable;
176 else if (tmp & R)
177 fldtab->weights = Rascii;
178 fldtab->flags |= tmp;
179 break;
180 case 'H':
181 PANIC = 0;
182 break;
183 case 'k':
184 fldtab_sz++;
185 fldtab = realloc(fldtab, fldtab_sz*sizeof(*fldtab));
186
187 setfield(optarg, ++ftpos, fldtab->flags);
188 break;
189 case 'm':
190 mflag = 1;
191 break;
192 case 'o':
193 outpath = optarg;
194 break;
195 case 's':
196 /* for GNU sort compatibility (this is our default) */
197 stable_sort = 1;
198 break;
199 case 'S':
200 stable_sort = 0;
201 break;
202 case 't':
203 if (SEP_FLAG)
204 usage("multiple field delimiters");
205 SEP_FLAG = 1;
206 d_mask[' '] &= ~FLD_D;
207 d_mask['\t'] &= ~FLD_D;
208 d_mask[(u_char)*optarg] |= FLD_D;
209 if (d_mask[(u_char)*optarg] & REC_D_F)
210 errx(2, "record/field delimiter clash");
211 break;
212 case 'R':
213 if (REC_D != '\n')
214 usage("multiple record delimiters");
215 if ('\n' == (REC_D = *optarg))
216 break;
217 d_mask['\n'] = d_mask[' '];
218 d_mask[REC_D] = REC_D_F;
219 break;
220 case 'T':
221 /* -T tmpdir */
222 tmpdir = optarg;
223 break;
224 case 'u':
225 UNIQUE = 1;
226 break;
227 case '?':
228 default:
229 usage(NULL);
230 }
231 }
232 if (cflag && argc > optind+1)
233 errx(2, "too many input files for -c option");
234 if (argc - 2 > optind && !strcmp(argv[argc-2], "-o")) {
235 outpath = argv[argc-1];
236 argc -= 2;
237 }
238 if (mflag && argc - optind > (MAXFCT - (16+1))*16)
239 errx(2, "too many input files for -m option");
240 for (i = optind; i < argc; i++) {
241 /* allow one occurrence of /dev/stdin */
242 if (!strcmp(argv[i], "-") || !strcmp(argv[i], _PATH_STDIN)) {
243 if (stdinflag)
244 warnx("ignoring extra \"%s\" in file list",
245 argv[i]);
246 else
247 stdinflag = 1;
248
249 /* change to /dev/stdin if '-' */
250 if (argv[i][0] == '-')
251 argv[i] = _PATH_STDIN;
252
253 } else if ((ch = access(argv[i], R_OK)))
254 err(2, "%s", argv[i]);
255 }
256 if (!(fldtab->flags & (I|D|N) || fldtab[1].icol.num)) {
257 SINGL_FLD = 1;
258 fldtab[0].icol.num = 1;
259 } else {
260 if (!fldtab[1].icol.num) {
261 fldtab[0].flags &= ~(BI|BT);
262 setfield("1", ++ftpos, fldtab->flags);
263 }
264 fldreset(fldtab);
265 fldtab[0].flags &= ~F;
266 }
267 settables(fldtab[0].flags);
268 num_init();
269 fldtab->weights = gweights;
270 if (optind == argc) {
271 static const char * const names[] = { _PATH_STDIN, NULL };
272
273 filelist.names = names;
274 optind--;
275 } else
276 filelist.names = (const char * const *) &argv[optind];
277
278 if (SINGL_FLD)
279 get = makeline;
280 else
281 get = makekey;
282
283 if (cflag) {
284 order(&filelist, get, fldtab);
285 /* NOT REACHED */
286 }
287 if (!outpath) {
288 (void)snprintf(toutpath,
289 sizeof(toutpath), "%sstdout", _PATH_DEV);
290 outfile = outpath = toutpath;
291 outfp = stdout;
292 } else if (!(ch = access(outpath, 0)) &&
293 strncmp(_PATH_DEV, outpath, 5)) {
294 struct sigaction act;
295 static const int sigtable[] = {SIGHUP, SIGINT, SIGPIPE,
296 SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, 0};
297 int outfd;
298 errno = 0;
299 if (access(outpath, W_OK))
300 err(2, "%s", outpath);
301 (void)snprintf(toutpath, sizeof(toutpath), "%sXXXXXX",
302 outpath);
303 if ((outfd = mkstemp(toutpath)) == -1)
304 err(2, "Cannot create temporary file `%s'", toutpath);
305 if ((outfp = fdopen(outfd, "w")) == NULL)
306 err(2, "Cannot open temporary file `%s'", toutpath);
307 outfile = toutpath;
308 (void)atexit(cleanup);
309 act.sa_handler = onsignal;
310 (void) sigemptyset(&act.sa_mask);
311 act.sa_flags = SA_RESTART | SA_RESETHAND;
312 for (i = 0; sigtable[i]; ++i) /* always unlink toutpath */
313 sigaction(sigtable[i], &act, 0);
314 } else
315 outfile = outpath;
316
317 if (outfp == NULL && (outfp = fopen(outfile, "w")) == NULL)
318 err(2, "output file %s", outfile);
319
320 if (mflag) {
321 fmerge(-1, 0, &filelist, argc-optind, get, outfp, putline,
322 fldtab);
323 } else
324 fsort(-1, 0, 0, &filelist, argc-optind, outfp, fldtab);
325
326 if (outfile != outpath) {
327 if (access(outfile, 0))
328 err(2, "%s", outfile);
329 (void)unlink(outpath);
330 if (link(outfile, outpath))
331 err(2, "cannot link %s: output left in %s",
332 outpath, outfile);
333 (void)unlink(outfile);
334 }
335 exit(0);
336 }
337
338 static void
339 onsignal(sig)
340 int sig;
341 {
342 cleanup();
343 }
344
345 static void
346 cleanup()
347 {
348 if (toutpath[0])
349 (void)unlink(toutpath);
350 }
351
352 static void
353 usage(msg)
354 const char *msg;
355 {
356 if (msg != NULL)
357 (void)fprintf(stderr, "sort: %s\n", msg);
358 (void)fprintf(stderr, "usage: [-o output] [-cmubdfinrsS] [-t char] ");
359 (void)fprintf(stderr, "[-R char] [-k keydef] ... [files]\n");
360 exit(2);
361 }
362