summaryrefslogtreecommitdiff
path: root/regress/lib/libpthread/blocked_fifo/blocked_fifo.c
blob: c5dc63bc45d3819f859f55864b317f1908525b17 (plain)
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
/*	$OpenBSD: blocked_fifo.c,v 1.1 2012/03/19 17:41:57 oga Exp $	*/
/*
 * Copyright (c) 2012 Owain G. Ainsworth <oga@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Test fifo opening blocking the file descriptor table and thus all other
 * opens in the process.
 * Symptoms are that the main thread will sleep on fifor (in the fifo open) and
 * the deadlocker on fdlock (in open of any other file).
 */

#include <sys/types.h>
#include <sys/stat.h>

#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include "test.h"

#define FIFO	"/tmp/pthread.fifo"
#define FILE	"/etc/services"	/* just any file to deadlock on */

static void *
deadlock_detector(void *arg)
{
	sleep(10);
	unlink(FIFO);
	PANIC("deadlock detected");
}

static void *
fifo_deadlocker(void *arg)
{
	int	fd;

	/* let other fifo open start */
	sleep(3);

	/* open a random temporary file, if we don't deadlock this'll succeed */
	CHECKe(fd = open(FILE, O_RDONLY));
	CHECKe(close(fd));

	/* open fifo to unblock other thread */
	CHECKe(fd = open(FIFO, O_WRONLY));

	return ((caddr_t)NULL + errno);
}

int
main(int argc, char *argv[])
{
	pthread_t	 deadlock_thread, deadlock_finder;
	int		 fd;

	CHECKe(mkfifo(FIFO, S_IRUSR | S_IWUSR));

	CHECKr(pthread_create(&deadlock_thread, NULL,
	    fifo_deadlocker, NULL));
	CHECKr(pthread_create(&deadlock_finder, NULL,
	    deadlock_detector, NULL));

	/* Open fifo (this will sleep until we have readers */
	CHECKe(fd = open(FIFO, O_RDONLY));

	CHECKr(pthread_join(deadlock_thread, NULL));

	unlink(FIFO);

	SUCCEED;
}