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