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

  • SEARCH
  • Home
  • 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 671469
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T00:22:37+00:00 2026-05-14T00:22:37+00:00

Sockets on Linux question I have a worker thread that is blocked on an

  • 0

Sockets on Linux question

I have a worker thread that is blocked on an accept() call. It simply waits for an incoming network connection, handles it, and then returns to listening for the next connection.

When it is time for the program to exit, how do I signal this network worker thread (from the main thread) to return from the accept() call while still being able to gracefully exit its loop and handle its cleanup code.

Some things I tried:

  1. pthread_kill to send a signal. Feels kludgy to do this, plus it doesn’t reliably allow the thread to do it’s shutdown logic. Also makes the program terminate as well. I’d like to avoid signals if at all possible.

  2. pthread_cancel. Same as above. It’s a harsh kill on the thread. That, and the thread may be doing something else.

  3. Closing the listen socket from the main thread in order to make accept() abort. This doesn’t reliably work.

Some constraints:

If the solution involves making the listen socket non-blocking, that is fine. But I don’t want to accept a solution that involves the thread waking up via a select call every few seconds to check the exit condition.

The thread condition to exit may not be tied to the process exiting.

Essentially, the logic I am going for looks like this.

void* WorkerThread(void* args)
{
    DoSomeImportantInitialization();  // initialize listen socket and some thread specific stuff

    while (HasExitConditionBeenSet()==false)
    {
        listensize = sizeof(listenaddr);
        int sock = accept(listensocket, &listenaddr, &listensize);

        // check if exit condition has been set using thread safe semantics
        if (HasExitConditionBeenSet())
        {
            break;
        }

        if (sock < 0)
        {
            printf("accept returned %d (errno==%d)\n", sock, errno);
        }
        else
        {
            HandleNewNetworkCondition(sock, &listenaddr);
        }
    }

    DoSomeImportantCleanup(); // close listen socket, close connections, cleanup etc..
    return NULL;
}

void SignalHandler(int sig)
{
    printf("Caught CTRL-C\n");
}

void NotifyWorkerThreadToExit(pthread_t thread_handle)
{
    // signal thread to exit
}

int main()
{
    void* ptr_ret= NULL;
    pthread_t workerthread_handle = 0;

    pthread_create(&workerthread, NULL, WorkerThread, NULL);

    signal(SIGINT, SignalHandler);

    sleep((unsigned int)-1); // sleep until the user hits ctrl-c

    printf("Returned from sleep call...\n");

    SetThreadExitCondition(); // sets global variable with barrier that worker thread checks on

    // this is the function I'm stalled on writing
    NotifyWorkerThreadToExit(workerthread_handle);

    // wait for thread to exit cleanly
    pthread_join(workerthread_handle, &ptr_ret);

    DoProcessCleanupStuff();

}
  • 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-14T00:22:38+00:00Added an answer on May 14, 2026 at 12:22 am

    You can use a pipe to notify the thread that you want it to exit. Then you can have a select() call which selects on both the pipe and the listening socket.

    For example (compiles but not fully tested):

    // NotifyPipe.h
    #ifndef NOTIFYPIPE_H_INCLUDED
    #define NOTIFYPIPE_H_INCLUDED
    
    class NotifyPipe
    {
            int m_receiveFd;
            int m_sendFd;
    
        public:
            NotifyPipe();
            virtual ~NotifyPipe();
    
            int receiverFd();
            void notify();
    };
    
    #endif // NOTIFYPIPE_H_INCLUDED
    
    // NotifyPipe.cpp
    
    #include "NotifyPipe.h"
    
    #include <unistd.h>
    #include <assert.h>
    #include <fcntl.h>
    
    NotifyPipe::NotifyPipe()
    {
        int pipefd[2];
        int ret = pipe(pipefd);
        assert(ret == 0); // For real usage put proper check here
        m_receiveFd = pipefd[0];
        m_sendFd = pipefd[1];
        fcntl(m_sendFd,F_SETFL,O_NONBLOCK);
    }
    
    
    NotifyPipe::~NotifyPipe()
    {
        close(m_sendFd);
        close(m_receiveFd);
    }
    
    
    int NotifyPipe::receiverFd()
    {
        return m_receiveFd;
    }
    
    
    void NotifyPipe::notify()
    {
        write(m_sendFd,"1",1);
    }
    

    Then select with receiverFd(), and notify for termination using notify().

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 464k
  • Answers 464k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The PHP session is stored in webserver's memory while JavaScript… May 16, 2026 at 12:56 am
  • Editorial Team
    Editorial Team added an answer This effect is very CPU intensive, as it is software-rendered… May 16, 2026 at 12:56 am
  • Editorial Team
    Editorial Team added an answer As mentioned above, do not store credit card information in… May 16, 2026 at 12:56 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.