OpenSolaris_b135/lib/libc/port/stdio/tmpfile.c

Compare this file to the similar file:
Show the results in this format:

/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1988 AT&T	*/
/*	  All Rights Reserved  	*/

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 *	tmpfile - return a pointer to an update file that can be
 *		used for scratch. The file will automatically
 *		go away if the program using it terminates.
 */

#include "lint.h"
#include "mtlib.h"
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <thread.h>
#include <synch.h>
#include <sys/stat.h>

static char seed[] = { 'a', 'a', 'a', '\0' };
static mutex_t seed_lk = DEFAULTMUTEX;

#define	XS "\bXXXXXX"		/* a '\b' character is prepended to this */
				/* string to avoid conflicts with names */
				/* generated by tmpnam() */
/*ARGSUSED*/
static FILE *
_common(boolean_t large_file)
{
	char	tfname[L_tmpnam];
	FILE	*p;
	char	*q;
	int	mkret;
	mode_t	current_umask;

	(void) strcpy(tfname, P_tmpdir);
	lmutex_lock(&seed_lk);
	(void) strcat(tfname, seed);
	(void) strcat(tfname, XS);

	q = seed;
	while (*q == 'z')
		*q++ = 'a';
	if (*q != '\0')
		++*q;
	lmutex_unlock(&seed_lk);

#if !defined(_LP64)
	if (large_file == B_TRUE) {
		if ((mkret = mkstemp64(tfname)) == -1)
			return (NULL);
	} else
#endif
		if ((mkret = mkstemp(tfname)) == -1)
			return (NULL);

	(void) unlink(tfname);
	current_umask = umask(0777);
	(void) umask(current_umask);
	(void) fchmod(mkret, 0666 & ~current_umask);
	if ((p = fdopen(mkret, "w+")) == NULL) {
		(void) close(mkret);
		return (NULL);
	}

	return (p);
}

#if !defined(_LP64)
FILE *
tmpfile64(void)
{
	return (_common(B_TRUE));
}
#endif	/* _LP64 */

/*
 * This is a bit confusing -- some explanation is in order.
 *
 * When we're compiled 64-bit, there's no point in distinguishing
 * a "large" file from a "small" file -- they're all "large".
 * The argument we pass to '_common' is ignored -- we always call
 * mkstemp which will just do the right thing for us.
 */
FILE *
tmpfile(void)
{
	return (_common(B_FALSE));
}