Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a process running?

I have a process that starts several threads which do some stuff, listen to some ports, etc.

After it starts all threads, the main thread currently goes into an infinite loop:

It's something like:

int main()
{
   //start threads
   while (true)
   {
      sleep(1000);
   }
}

The extra sleep assures the main thread doesn't eat the processor.

Is this approach ok? Is there an industry standard on how a process is kept alivet? Thanks.

EDIT: Some clarifications:

  • the threads are listeners, so a join or WaitForSingleObject isn't an option. Usually I could use join here, but the threads are started by a third client library and I don't have any control over them.
  • doing some processing in the main thread doesn't make sense from a design point of view.
like image 297
AMCoder Avatar asked Jul 01 '26 02:07

AMCoder


2 Answers

. Taken partially from the Linux Daemon Writing HOWTO, I assume you want something like this:

int main() {
    pid_t pid;

    /* Fork off the parent process */       
    pid = fork();
    if (pid < 0) {
            exit(EXIT_FAILURE);
    }
    /* If we got a good PID, then
       we can exit the parent process. */
    if (pid > 0) {
            exit(EXIT_SUCCESS);
    }
    // now start threads & do the work

    for( thread *t : threads ) {
            join( t );
    }

    return 0;
}

This way the main process will exit, child process will spawn threads which will do the work. In the end the child process will wait for those threads to finish before exiting itself.

like image 141
Stan Avatar answered Jul 02 '26 14:07

Stan


I'd suggest you to have your main thread waiting for the termination of the others:

int main( ) {
  // start threads
  for( thread *t : threads ) {
    join( t );
  }
  // finalize everything or restart the thread
  return 0;
}

If you're using POSIX threads, the pthread_join function will do this.

like image 25
peoro Avatar answered Jul 02 '26 15:07

peoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!