For work i need to write a tcp daemon to respond to our client software and was wondering if any one had any tips on the best way to go about this.
Should i fork for every new connection as normally i would use threads?
You can start by naming the application code that will run as a daemon as test.c, and the code that you will create the daemon function as daemon.c. To create a daemon, you need a background process whose parent process is init. In the code above, _daemon creates a child process and then kills the parent process.
Here's how you can code your own daemons on Linux. Daemons are processes that do not run directly under the control of the user but serve in the background. Usually, they start on system startup and run continuously until the system shuts down.
They are utility programs that run silently in the background to monitor and take care of certain subsystems to ensure that the operating system runs properly. A printer daemon monitors and takes care of printing services. A network daemon monitors and maintains network communications, and so on.
To identify a daemon, look for a process that ends with the letter d. It’s a general Linux rule that the names of daemons end this way. There are many ways to catch a glimpse of a running daemon. They can be seen in process listings through ps , top, or htop.
It depends on your application. Threads and forking can both be perfectly valid approaches, as well as the third option of a single-threaded event-driven model. If you can explain a bit more about exactly what you're writing, it would help when giving advice.
For what it's worth, here are a few general guidelines:
Generally forking will be the easiest to implement, as you can essentially ignore all other connections once you fork; threads the next hardest due to the additional synchronization requirements; the event loop more difficult due to the need to turn your processing into a state machine; and multiple threads running event loops the most difficult of them all (due to combining other factors).
I'd suggest forking for connections over threads any day. The problem with threads is the shared memory space, and how easy it is to manipulate the memory of another thread. With forked processes, any communication between the processes has to be intentionally done by you.
Just searched and found this SO answer: What is the purpose of fork?. You obviously know the answer to that, but the #1 answer in that thread has good points on the advantages of fork().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With