user_0
user_0

Reputation: 3363

Service under linux, a modern approach?

The situation: a small new project of a service listening on socket.

Preliminary study: this answer how to make a process daemon and the link in the answer: http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html

Good, everything fine.
Now, for the listening part I have no problems, but for threads I started to watch C++11 specs. So I included:

#include <thread>

This is nice, just calling std::thread, I can open a thread on new connections.

So I was just wondering, is the fork part still good in C++11?

Is there a newer approach to building a Linux service, or is the how-to still good?

Upvotes: 2

Views: 208

Answers (2)

wallyk
wallyk

Reputation: 57784

fork works well in any language on Linux. Separate processes not the same as threads, but they do have a few things in common.

fork() makes a nearly-identical copy of the current process. Including all its file handles, memory maps, heap, stack, etc. However, only the thread which called fork() runs in the child.

A new thread runs in the same process, and has potential access to all its resources, including heap, file handles, semaphores, etc. This is potentially a contention issue since other threads manipulating the same resources can cause hard-to-find behavior.

A daemon is little more than a process which has detached from a terminal and so can continue to run after the initiating user has logged out. Presumably it makes its own arrangements for writing errors (like into a log), sensing input, processing requests, etc.

Upvotes: 1

SergeyA
SergeyA

Reputation: 62603

fork() was never part of any C++ standard, and I do not see it ever to become a part of it. There are certain benefits and drawbacks of doing your service as a multi-process or multi-threaded application. The main benefit of multi-process is resiliance - crash in one service handler will not affect another, while crash in a multithreaded application will kill at all. On the other hand, multithreaded applications have more ways (and those are faster) to communicate to with each other then the ones available to multi-process apps.

The choice is yours, but one thing you NEVER want to do is to mix forks and threads together.

Upvotes: 2

Related Questions