misc_utils.c 2.1 KB
Newer Older
1
/*
M
 
Marc G. Fournier 已提交
2
 * misc_utils.c --
3
 *
M
 
Marc G. Fournier 已提交
4
 * This file defines miscellaneous PostgreSQL utility functions.
5
 *
B
Bruce Momjian 已提交
6
 * Copyright (C) 1999, Massimo Dal Zotto <dz@cs.unitn.it>
M
 
Marc G. Fournier 已提交
7 8 9
 *
 * This file is distributed under the GNU General Public License
 * either version 2, or (at your option) any later version.
10 11
 */

12 13
#include "postgres.h"

14
#include <unistd.h>
B
Hi,  
Bruce Momjian 已提交
15
#include <signal.h>
16

B
Hi,  
Bruce Momjian 已提交
17 18 19 20 21 22 23
#include "access/heapam.h"
#include "access/htup.h"
#include "access/relscan.h"
#include "access/skey.h"
#include "access/tupdesc.h"
#include "catalog/catname.h"
#include "catalog/pg_listener.h"
24
#include "commands/async.h"
25
#include "fmgr.h"
B
Hi,  
Bruce Momjian 已提交
26
#include "storage/lmgr.h"
27
#include "utils/fmgroids.h"
B
Hi,  
Bruce Momjian 已提交
28 29
#include "utils/rel.h"
#include "utils/tqual.h"
30 31

#include "misc_utils.h"
B
Hi,  
Bruce Momjian 已提交
32

33 34 35 36

int
backend_pid()
{
37
	return getpid();
38 39 40 41 42
}

int
unlisten(char *relname)
{
43 44
	Async_Unlisten(relname, getpid());
	return 0;
45 46 47
}

int
48
int4max(int x, int y)
49
{
50
	return Max(x, y);
51 52 53
}

int
54
int4min(int x, int y)
55
{
56
	return Min(x, y);
57 58
}

B
Hi,  
Bruce Momjian 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71
/*
 * Return the number of active listeners on a relation name.
 */
int
active_listeners(text *relname)
{
	HeapTuple	lTuple;
	Relation	lRel;
	HeapScanDesc sRel;
	TupleDesc	tdesc;
	ScanKeyData key;
	Datum		d;
	bool		isnull;
72 73
	int			len,
				pid;
B
Hi,  
Bruce Momjian 已提交
74 75 76 77
	int			count = 0;
	int			ourpid = getpid();
	char		listen_name[NAMEDATALEN];

78
	lRel = heap_openr(ListenerRelationName, AccessShareLock);
B
Hi,  
Bruce Momjian 已提交
79 80
	tdesc = RelationGetDescr(lRel);

81 82
	if (relname && (VARSIZE(relname) > VARHDRSZ))
	{
83
		MemSet(listen_name, 0, NAMEDATALEN);
84
		len = Min(VARSIZE(relname) - VARHDRSZ, NAMEDATALEN - 1);
85
		memcpy(listen_name, VARDATA(relname), len);
86 87 88 89
		ScanKeyInit(&key,
					Anum_pg_listener_relname,
					BTEqualStrategyNumber, F_NAMEEQ,
					PointerGetDatum(listen_name));
90
		sRel = heap_beginscan(lRel, SnapshotNow, 1, &key);
B
Hi,  
Bruce Momjian 已提交
91
	}
92
	else
93
		sRel = heap_beginscan(lRel, SnapshotNow, 0, (ScanKey) NULL);
B
Hi,  
Bruce Momjian 已提交
94

95
	while ((lTuple = heap_getnext(sRel, ForwardScanDirection)) != NULL)
B
Hi,  
Bruce Momjian 已提交
96 97 98
	{
		d = heap_getattr(lTuple, Anum_pg_listener_pid, tdesc, &isnull);
		pid = DatumGetInt32(d);
99
		if ((pid == ourpid) || (kill(pid, SIGTSTP) == 0))
B
Hi,  
Bruce Momjian 已提交
100 101 102 103
			count++;
	}
	heap_endscan(sRel);

104
	heap_close(lRel, AccessShareLock);
B
Hi,  
Bruce Momjian 已提交
105 106 107

	return count;
}