Home | History | Annotate | Line # | Download | only in sort
sort.c revision 1.36
      1 /*	$NetBSD: sort.c,v 1.36 2004/02/17 02:28:29 itojun 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.36 2004/02/17 02:28:29 itojun 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 	memset(fldtab, 0, fldtab_sz * sizeof(*fldtab));
    156 	ftpos = fldtab;
    157 
    158 	fixit(&argc, argv);
    159 
    160 	if (!(tmpdir = getenv("TMPDIR")))
    161 		tmpdir = _PATH_TMP;
    162 
    163 	while ((ch = getopt(argc, argv, "bcdfik:mHno:rR:sSt:T:ux")) != -1) {
    164 		switch (ch) {
    165 		case 'b':
    166 			fldtab->flags |= BI | BT;
    167 			break;
    168 		case 'c':
    169 			cflag = 1;
    170 			break;
    171 		case 'd': case 'f': case 'i': case 'n': case 'r':
    172 			tmp |= optval(ch, 0);
    173 			if ((tmp & R) && (tmp & F))
    174 				fldtab->weights = RFtable;
    175 			else if (tmp & F)
    176 				fldtab->weights = Ftable;
    177 			else if (tmp & R)
    178 				fldtab->weights = Rascii;
    179 			fldtab->flags |= tmp;
    180 			break;
    181 		case 'H':
    182 			PANIC = 0;
    183 			break;
    184 		case 'k':
    185 			fldtab_sz++;
    186 			fldtab = realloc(fldtab, fldtab_sz*sizeof(*fldtab));
    187 
    188 			setfield(optarg, ++ftpos, fldtab->flags);
    189 			break;
    190 		case 'm':
    191 			mflag = 1;
    192 			break;
    193 		case 'o':
    194 			outpath = optarg;
    195 			break;
    196 		case 's':
    197 			/* for GNU sort compatibility (this is our default) */
    198 			stable_sort = 1;
    199 			break;
    200 		case 'S':
    201 			stable_sort = 0;
    202 			break;
    203 		case 't':
    204 			if (SEP_FLAG)
    205 				usage("multiple field delimiters");
    206 			SEP_FLAG = 1;
    207 			d_mask[' '] &= ~FLD_D;
    208 			d_mask['\t'] &= ~FLD_D;
    209 			d_mask[(u_char)*optarg] |= FLD_D;
    210 			if (d_mask[(u_char)*optarg] & REC_D_F)
    211 				errx(2, "record/field delimiter clash");
    212 			break;
    213 		case 'R':
    214 			if (REC_D != '\n')
    215 				usage("multiple record delimiters");
    216 			if ('\n' == (REC_D = *optarg))
    217 				break;
    218 			d_mask['\n'] = d_mask[' '];
    219 			d_mask[REC_D] = REC_D_F;
    220 			break;
    221 		case 'T':
    222 			/* -T tmpdir */
    223 			tmpdir = optarg;
    224 			break;
    225 		case 'u':
    226 			UNIQUE = 1;
    227 			break;
    228 		case '?':
    229 		default:
    230 			usage(NULL);
    231 		}
    232 	}
    233 	if (cflag && argc > optind+1)
    234 		errx(2, "too many input files for -c option");
    235 	if (argc - 2 > optind && !strcmp(argv[argc-2], "-o")) {
    236 		outpath = argv[argc-1];
    237 		argc -= 2;
    238 	}
    239 	if (mflag && argc - optind > (MAXFCT - (16+1))*16)
    240 		errx(2, "too many input files for -m option");
    241 	for (i = optind; i < argc; i++) {
    242 		/* allow one occurrence of /dev/stdin */
    243 		if (!strcmp(argv[i], "-") || !strcmp(argv[i], _PATH_STDIN)) {
    244 			if (stdinflag)
    245 				warnx("ignoring extra \"%s\" in file list",
    246 				    argv[i]);
    247 			else
    248 				stdinflag = 1;
    249 
    250 			/* change to /dev/stdin if '-' */
    251 			if (argv[i][0] == '-')
    252 				argv[i] = _PATH_STDIN;
    253 
    254 		} else if ((ch = access(argv[i], R_OK)))
    255 			err(2, "%s", argv[i]);
    256 	}
    257 	if (!(fldtab->flags & (I|D|N) || fldtab[1].icol.num)) {
    258 		SINGL_FLD = 1;
    259 		fldtab[0].icol.num = 1;
    260 	} else {
    261 		if (!fldtab[1].icol.num) {
    262 			fldtab[0].flags &= ~(BI|BT);
    263 			setfield("1", ++ftpos, fldtab->flags);
    264 		}
    265 		fldreset(fldtab);
    266 		fldtab[0].flags &= ~F;
    267 	}
    268 	settables(fldtab[0].flags);
    269 	num_init();
    270 	fldtab->weights = gweights;
    271 	if (optind == argc) {
    272 		static const char * const names[] = { _PATH_STDIN, NULL };
    273 
    274 		filelist.names = names;
    275 		optind--;
    276 	} else
    277 		filelist.names = (const char * const *) &argv[optind];
    278 
    279 	if (SINGL_FLD)
    280 		get = makeline;
    281 	else
    282 		get = makekey;
    283 
    284 	if (cflag) {
    285 		order(&filelist, get, fldtab);
    286 		/* NOT REACHED */
    287 	}
    288 	if (!outpath) {
    289 		(void)snprintf(toutpath,
    290 		    sizeof(toutpath), "%sstdout", _PATH_DEV);
    291 		outfile = outpath = toutpath;
    292 		outfp = stdout;
    293 	} else if (!(ch = access(outpath, 0)) &&
    294 	    strncmp(_PATH_DEV, outpath, 5)) {
    295 		struct sigaction act;
    296 		static const int sigtable[] = {SIGHUP, SIGINT, SIGPIPE,
    297 		    SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, 0};
    298 		int outfd;
    299 		errno = 0;
    300 		if (access(outpath, W_OK))
    301 			err(2, "%s", outpath);
    302 		(void)snprintf(toutpath, sizeof(toutpath), "%sXXXXXX",
    303 		    outpath);
    304 		if ((outfd = mkstemp(toutpath)) == -1)
    305 			err(2, "Cannot create temporary file `%s'", toutpath);
    306 		if ((outfp = fdopen(outfd, "w")) == NULL)
    307 			err(2, "Cannot open temporary file `%s'", toutpath);
    308 		outfile = toutpath;
    309 		(void)atexit(cleanup);
    310 		act.sa_handler = onsignal;
    311 		(void) sigemptyset(&act.sa_mask);
    312 		act.sa_flags = SA_RESTART | SA_RESETHAND;
    313 		for (i = 0; sigtable[i]; ++i)	/* always unlink toutpath */
    314 			sigaction(sigtable[i], &act, 0);
    315 	} else
    316 		outfile = outpath;
    317 
    318 	if (outfp == NULL && (outfp = fopen(outfile, "w")) == NULL)
    319 		err(2, "output file %s", outfile);
    320 
    321 	if (mflag) {
    322 		fmerge(-1, 0, &filelist, argc-optind, get, outfp, putline,
    323 			fldtab);
    324 	} else
    325 		fsort(-1, 0, 0, &filelist, argc-optind, outfp, fldtab);
    326 
    327 	if (outfile != outpath) {
    328 		if (access(outfile, 0))
    329 			err(2, "%s", outfile);
    330 		(void)unlink(outpath);
    331 		if (link(outfile, outpath))
    332 			err(2, "cannot link %s: output left in %s",
    333 			    outpath, outfile);
    334 		(void)unlink(outfile);
    335 	}
    336 	exit(0);
    337 }
    338 
    339 static void
    340 onsignal(sig)
    341 	int sig;
    342 {
    343 	cleanup();
    344 }
    345 
    346 static void
    347 cleanup()
    348 {
    349 	if (toutpath[0])
    350 		(void)unlink(toutpath);
    351 }
    352 
    353 static void
    354 usage(msg)
    355 	const char *msg;
    356 {
    357 	if (msg != NULL)
    358 		(void)fprintf(stderr, "sort: %s\n", msg);
    359 	(void)fprintf(stderr, "usage: [-o output] [-cmubdfinrsS] [-t char] ");
    360 	(void)fprintf(stderr, "[-R char] [-k keydef] ... [files]\n");
    361 	exit(2);
    362 }
    363