Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3344888
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T01:07:18+00:00 2026-05-18T01:07:18+00:00

I’ve recently started learning Python (long time Java programmer here) and currently in the

  • 0

I’ve recently started learning Python (long time Java programmer here) and currently in the process of writing some simple server programs. The problem is, for a seemingly similar piece of code, the Java counterpart properly responds to the SIGINT signal (Ctrl+C) whereas the Python one doesn’t. This is seen when a separate thread is used to spawn the server. Code is as follows:

// Java code

package pkg;

import java.io.*;
import java.net.*;

public class ServerTest {

    public static void main(final String[] args) throws Exception {
        final Thread t = new Server();
        t.start();
    }

}

class Server extends Thread {

    @Override
    public void run() {
        try {
            final ServerSocket sock = new ServerSocket(12345);
            while(true) {
                final Socket clientSock = sock.accept();
                clientSock.close();
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

}

and Python code:

# Python code
import threading, sys, socket, signal

def startserver():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 12345))
    s.listen(1)
    while True:
        csock, caddr = s.accept()
        csock.sendall('Get off my lawn kids...\n')
        csock.close()

if __name__ == '__main__':
    try:
        t = threading.Thread(target=startserver)
        t.start()
    except:
        sys.exit(1)

In both the above code snippets, I create a simple server which listens to TCP requests on the given port. When Ctrl+C is pressed in case of the Java code, the JVM exits whereas in the case of the Python code, all I get is a ^C at the shell. The only way I can stop the server is press Ctrl+Z and then manually kill the process.

So I come up with a plan; why not have a sighandler which listens for Ctrl+Z and quits the application? Cool, so I come up with:

import threading, sys, socket, signal

def startserver():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 12345))
    s.listen(1)
    while True:
        csock, caddr = s.accept()
        csock.sendall('Get off my lawn kids...\n')
        csock.close()

def ctrlz_handler(*args, **kwargs):
    sys.exit(1)

if __name__ == '__main__':
    try:
        signal.signal(signal.SIGTSTP, ctrlz_handler)
        t = threading.Thread(target=startserver)
        t.start()
    except:
        sys.exit(1)

But now, it seems as I’ve made the situation even worse! Now pressing Ctrl+C at the shell emits ‘^C’ and pressing Ctrl+Z at the shell emits ‘^Z’.

So my question is, why this weird behaviour? I’d probably have multiple server processes running as separate threads in the same process so any clean way of killing the server when the process receives SIGINT? BTW using Python 2.6.4 on Ubuntu.

TIA,
sasuke

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T01:07:18+00:00Added an answer on May 18, 2026 at 1:07 am

    Several issues:

    • Don’t catch all exceptions and silently exit. That’s the worst possible thing you can do.

    • Unless you really know what you’re doing, never catch SIGTSTP. It’s not a signal meant for applications to intercept, and if you’re catching it, chances are you’re doing something wrong.

    • KeyboardInterrupt is only sent to the initial thread of the program, and never to other threads. This is done for a couple reasons. Generally, you want to deal with ^C in a single place, and not in a random, arbitrary thread that happens to receive the exception. Also, it helps guarantee that, in normal operation, most threads never receive asynchronous exceptions; this is useful since (in all languages, including Java) they’re very hard to deal with reliably.

    • You’re never going to see the KeyboardInterrupt here, because your main thread exits immediately after starting the secondary thread. There’s no main thread to receive the exception, and it’s simply discarded.

    The fix is two-fold: keep the main thread around, so the KeyboardInterrupt has somewhere to go, and only catch KeyboardInterrupt, not all exceptions.


    import threading, sys, socket, signal, time
    
    def startserver():
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('', 12345))
        s.listen(1)
        while True:
            csock, caddr = s.accept()
            csock.sendall('Get off my lawn kids...\n')
            csock.close()
    
    if __name__ == '__main__':
        try:
            t = threading.Thread(target=startserver)
            t.start()
    
            # Wait forever, so we can receive KeyboardInterrupt.
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print "^C received"
            sys.exit(1)
    
        # We never get here.
        raise RuntimeError, "not reached"
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.