Skip to content

Commit 2aac74c

Browse files
committed
Create tcpServer_signals.py
1 parent adeef4d commit 2aac74c

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

bin/tcpServer_signals.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#! /bin/python
2+
# Program for messing with tcp server and signals
3+
4+
import sys, signal, socket, random
5+
6+
# set our socket as a global variable
7+
s = 0
8+
9+
def signal_handler(signum, frm) :
10+
global s
11+
print "SIGINT received"
12+
print "Shutting down listener gracefully."
13+
# now shut it down
14+
s.close()
15+
print "Exiting now."
16+
sys.exit()
17+
18+
def tcp_listner():
19+
global s
20+
# pick a random port and fetch host
21+
port = random.randrange(18000,65535,1)
22+
host = socket.gethostname()
23+
24+
# point SIGINT to signal_handler
25+
signal.signal(signal.SIGINT, signal_handler)
26+
27+
print "Opening port %d." % (port)
28+
try:
29+
# try to create a socket
30+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
31+
except socket.error:
32+
print 'Socket creation failed!'
33+
sys.exit()
34+
35+
print "Binding to host %s port %d" % (host,port)
36+
s.bind((host,port))
37+
# open up a listener that will accept 1 connection
38+
s.listen(1)
39+
40+
if __name__ == '__main__':
41+
print "Starting tcp listner..."
42+
tcp_listner()
43+
44+
# SIGINT is the signal for program interupt
45+
signal.signal(signal.SIGINT, signal_handler)
46+
47+
# and now we wait
48+
while True:
49+
pass

0 commit comments

Comments
 (0)