This document provides instructions on how to write a daemon process in Linux using C and GCC. It discusses the basic structure needed for a daemon, including forking the parent process, changing the file mode mask, opening logs, creating a session ID, changing the working directory, closing standard file descriptors, initialization, and an infinite loop structure. It provides code examples for each step and a complete sample daemon implementation incorporating all the elements.
Installing and Configuring Domino 10 on CentOS 7Devin Olson
Instructions on how to do a base-level installation of IBM / HCL's Domino 10 (10.0.1) server on a Debial-based (Red Hat, CentOS, etc) Linux Server.
Includes partitioning, network configuration, ssh installation & configuration, group and user creation, minimal packages, firewall configuration, sticky bits, and more.
Reusing your existing software on Android
1. Runnig the existing software on Android
1.1 Rebuilding by Android tool chain
1.2 Running the binary as is
2. Running Android on your existing Linux environment
I show you 'Android on Ubuntu server'
Installing and Configuring Domino 10 on CentOS 7Devin Olson
Instructions on how to do a base-level installation of IBM / HCL's Domino 10 (10.0.1) server on a Debial-based (Red Hat, CentOS, etc) Linux Server.
Includes partitioning, network configuration, ssh installation & configuration, group and user creation, minimal packages, firewall configuration, sticky bits, and more.
Reusing your existing software on Android
1. Runnig the existing software on Android
1.1 Rebuilding by Android tool chain
1.2 Running the binary as is
2. Running Android on your existing Linux environment
I show you 'Android on Ubuntu server'
Thinking outside the box, learning a little about a lotMark Broadbent
Being a SQL specialist is not enough. Windows and the interfaces SQL consumes are becoming ever more complex. Being aware of these technologies and beyond can make you a better DBA. You will learn how to become a DBA 2.5, SQL Enterprise name resolution strategies, create your own private VSAN & VCluster, fail instances BETWEEN separate clusters and use the CLR to manage the OS from SQL.
Add a bit of ACID to Cassandra. Cassandra Summit EU 2014odnoklassniki.ru
OK.ru is one of the largest social networks for Russian-speaking audiences with 80+ million unique user’s visits monthly. ok.ru uses Cassandra since 2010 and made a number of improvements to C* 2.0 and 2.1 codebase. Until recent time more than 50 TB of data at Ok.ru OLTP systems was managed by Microsoft SQL Sever. It’s very expensive, hard to scale and cannot save us from outage if one of our data centers fail. We wanted a new, fast scalable and reliable storage for these data. These data has requirements to support ACID transactions, so we don’t have to rewrite all application code from scratch. С* does not support these transactions, only lightweight, so we implemented a new storage with ACID and selected features of SQL world by ourselves. Still, it has C* at its heart. We’ll discuss the internals of the new storage, what features of C* we had to alter and which to rewrite from scratch. We’ll also talk about its operational experience in production.
While probably the most prominent, Docker is not the only tool for building and managing containers. Originally meant to be a "chroot on steroids" to help debug systemd, systemd-nspawn provides a fairly uncomplicated approach to work with containers. Being part of systemd, it is available on most recent distributions out-of-the-box and requires no additional dependencies.
This deck will introduce a few concepts involved in containers and will guide you through the steps of building a container from scratch. The payload will be a simple service, which will be automatically activated by systemd when the first request arrives.
Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxConJérôme Petazzoni
Containers are everywhere. But what exactly is a container? What are they made from? What's the difference between LXC, butts-nspawn, Docker, and the other container systems out there? And why should we bother about specific filesystems?
In this talk, Jérôme will show the individual roles and behaviors of the components making up a container: namespaces, control groups, and copy-on-write systems. Then, he will use them to assemble a container from scratch, and highlight the differences (and likelinesses) with existing container systems.
Thinking outside the box, learning a little about a lotMark Broadbent
Being a SQL specialist is not enough. Windows and the interfaces SQL consumes are becoming ever more complex. Being aware of these technologies and beyond can make you a better DBA. You will learn how to become a DBA 2.5, SQL Enterprise name resolution strategies, create your own private VSAN & VCluster, fail instances BETWEEN separate clusters and use the CLR to manage the OS from SQL.
Add a bit of ACID to Cassandra. Cassandra Summit EU 2014odnoklassniki.ru
OK.ru is one of the largest social networks for Russian-speaking audiences with 80+ million unique user’s visits monthly. ok.ru uses Cassandra since 2010 and made a number of improvements to C* 2.0 and 2.1 codebase. Until recent time more than 50 TB of data at Ok.ru OLTP systems was managed by Microsoft SQL Sever. It’s very expensive, hard to scale and cannot save us from outage if one of our data centers fail. We wanted a new, fast scalable and reliable storage for these data. These data has requirements to support ACID transactions, so we don’t have to rewrite all application code from scratch. С* does not support these transactions, only lightweight, so we implemented a new storage with ACID and selected features of SQL world by ourselves. Still, it has C* at its heart. We’ll discuss the internals of the new storage, what features of C* we had to alter and which to rewrite from scratch. We’ll also talk about its operational experience in production.
While probably the most prominent, Docker is not the only tool for building and managing containers. Originally meant to be a "chroot on steroids" to help debug systemd, systemd-nspawn provides a fairly uncomplicated approach to work with containers. Being part of systemd, it is available on most recent distributions out-of-the-box and requires no additional dependencies.
This deck will introduce a few concepts involved in containers and will guide you through the steps of building a container from scratch. The payload will be a simple service, which will be automatically activated by systemd when the first request arrives.
Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxConJérôme Petazzoni
Containers are everywhere. But what exactly is a container? What are they made from? What's the difference between LXC, butts-nspawn, Docker, and the other container systems out there? And why should we bother about specific filesystems?
In this talk, Jérôme will show the individual roles and behaviors of the components making up a container: namespaces, control groups, and copy-on-write systems. Then, he will use them to assemble a container from scratch, and highlight the differences (and likelinesses) with existing container systems.
Real-World Docker: 10 Things We've Learned RightScale
Docker has taken the world of software by storm, offering the promise of a portable way to build and ship software - including software running in the cloud. The RightScale development team has been diving into Docker for several projects, and we'll share our lessons learned on using Docker for our cloud-based applications.
Big Data: Explore Hadoop and BigInsights self-study labCynthia Saracco
Want a quick tour of Apache Hadoop and InfoSphere BigInsights (IBM's Hadoop distribution)? Follow this self-study lab to get hands-on experience with HDFS, MapReduce jobs, BigSheets, Big SQL, and more. This lab was tested against the free BigInsights Quick Start Edition 3.0 VMware image.
So you’ve managed to get a foothold into the web server — now what? Privilege escalation can be an intimidating process for those unfamiliar with Linux systems or advanced penetration testing techniques. Servers are often cluttered with utilities, backups, and files; how do you find your way through to a root shell? Where are the first places an attacker might look for exploitable vulnerabilities? In this workshop, participants will learn about common privilege escalation paths on Linux systems, including sticky bits, shell escapes, wildcard injections, and how to identify vulnerable services. This presentation will demonstrate several techniques for those looking to improve their security skills.
(This was originally presented on February 22, 2010 at Day of Shecurity Boston 2019).
(This was originally presented on February 22, 2010 at Day of Shecurity Boston 2019).
(This was originally presented on February 22, 2010 at Day of Shecurity Boston 2019).
(This was originally presented at BSides Columbus 2019 on March 1, 2019.)
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
UiPath Test Automation using UiPath Test Suite series, part 4
Linux Daemon Writting
1. Linux Daemon Writing HOWTO
Devin Watson <mailto:dmwatson@comcast.net> v1.0, May 2004
This document shows how to write a daemon in Linux using GCC. Knowledge of Linux and a familiarity with C
are necessary to use this document. This HOWTO is Copyright by Devin Watson, under the terms of the BSD
License.
Contents
1 Introduction: What is a Daemon? 1
2 Getting Started 2
3 Planning Your Daemon 2
3.1 What Is It Going To Do? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
3.2 How Much Interaction? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
4 Basic Daemon Structure 2
4.1 Forking The Parent Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
4.2 Changing The File Mode Mask (Umask) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
4.3 Opening Logs For Writing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.4 Creating a Unique Session ID (SID) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.5 Changing The Working Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.6 Closing Standard File Descriptors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5 Writing the Daemon Code 6
5.1 Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.2 The Big Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
6 Putting It All Together 7
6.1 Complete Sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1 Introduction: What is a Daemon?
A daemon (or service) is a background process is designed to run autonomously,with little or no user in-
tervention. The Apache web server http daemon (httpd) is one such example of a daemon. It waits in the
background listening on specific ports and serves up pages, or processes scripts, based on the type of request.
Creating a daemon in Linux uses a specific set of rules in a given order. Knowing how they work will help you
understand how daemons operate in userland Linux, but can also operate with calls to the kernel. In fact,
a few daemons interface with kernel modules that work with hardware devices, such as external controller
2. 2. Getting Started 2
boards, printers, and PDAs. They are one of the fundamental building blocks in Linux that give it incredible
flexibility and power.
Throughout this HOWTO, a very simple daemon will be built in C. As we go along, more code will be
added, showing the proper order of execution required to get a daemon up and running.
2 Getting Started
First off, you’ll need the following packages installed on your Linux machine to develop daemons, specifically:
• GCC 3.2.2 or higher
• Linux Development headers and libraries
If your system does not already have these installed (not likely, but check anyway), you’ll need them to
develop the examples in this HOWTO. To find out what version of GCC you have installed, use:
gcc --version
3 Planning Your Daemon
3.1 What Is It Going To Do?
A daemon should do one thing, and do it well. That one thing may be as complex as managing hundreds of
mailboxes on multiple domains, or as simple as writing a report and calling sendmail to mail it out.
In any case, you should have a good plan as to what the daemon should do. If it is going to interoperate
with other daemons (which you may or may not be writing), this is something else to consider as well.
3.2 How Much Interaction?
Daemons should never have direct communication with a user through a terminal. In fact, a daemon
shouldn’t communicate directly with a user at all. All communication should pass through some sort of
interface (which you may or may not have to write), which can be as complex as a GTK+ GUI, or as simple
as a signal set.
4 Basic Daemon Structure
When a daemon starts up, it has to do some low-level housework to get itself ready for its real job. This
involves a few steps:
• Fork off the parent process
• Change file mode mask (umask)
• Open logs for writing
• Create a unique Session ID (SID)
• Change the current working directory to a safe place
3. 4. Basic Daemon Structure 3
• Close standard file descriptors
• Enter actual daemon code
4.1 Forking The Parent Process
A daemon is started either by the system itself or a user in a terminal or script. When it does start, the
process is just like any other executable on the system. To make it truly autonomous, a child process must
be created where the actual code is executed. This is known as forking, and it uses the fork() function:
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);
}
Notice the error check right after the call to fork(). When writing a daemon, you will have to code as
defensively as possible. In fact, a good percentage of the total code in a daemon consists of nothing but
error checking.
The fork() function returns either the process id (PID) of the child process (not equal to zero), or -1 on
failure. If the process cannot fork a child, then the daemon should terminate right here.
If fork() did succeed, the parent process must exit gracefully. This may seem strange to anyone who hasn’t
seen it, but by forking, the child process continues the execution from here on out in the code.
4.2 Changing The File Mode Mask (Umask)
In order to write to any files (including logs) created by the daemon, the file mode mask (umask) must be
changed to ensure that they can be written to or read from properly. This is similar to running umask from
the command line, but we do it programmatically here. We can use the umask() function to accomplish this:
pid_t pid, sid;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
/* Log failure (use syslog if possible) */
exit(EXIT_FAILURE);
}
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
4. 4. Basic Daemon Structure 4
/* Change the file mode mask */
umask(0);
By setting the umask to 0, we will have full access to the files generated by the daemon. Even if you aren’t
planning on using any files, it is a good idea to set the umask here anyway, just in case you will be accessing
files on the filesystem.
4.3 Opening Logs For Writing
This part is optional, but it is recommended that you open a log file somewhere in the system for writing.
This may be the only place you can look for debug information about your daemon.
4.4 Creating a Unique Session ID (SID)
From here, the child process must get a unique SID from the kernel in order to operate. Otherwise, the child
process becomes an orphan in the system. The pid t type, declared in the previous section, is also used to
create a new SID for the child process:
pid_t pid, sid;
/* 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);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log any failure */
exit(EXIT_FAILURE);
}
Again, the setsid() function has the same return type as fork(). We can apply the same error-checking
routine here to see if the function created the SID for the child process.
4.5 Changing The Working Directory
The current working directory should be changed to some place that is guaranteed to always be there.
Since many Linux distributions do not completely follow the Linux Filesystem Hierarchy standard, the only
directory that is guaranteed to be there is the root directory (/). We can do this using the chdir() function:
5. 4. Basic Daemon Structure 5
pid_t pid, sid;
/* 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);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log any failure here */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir(quot;/quot;)) < 0) {
/* Log any failure here */
exit(EXIT_FAILURE);
}
Once again, you can see the defensive coding taking place. The chdir() function returns -1 on failure, so be
sure to check for that after changing to the root directory within the daemon.
4.6 Closing Standard File Descriptors
One of the last steps in setting up a daemon is closing out the standard file descriptors (STDIN, STDOUT,
STDERR). Since a daemon must not use the terminal, these file descriptors are both redundant and a
potential security hazard.
The close() function can handle this for us:
pid_t pid, sid;
/* 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);
6. 5. Writing the Daemon Code 6
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log any failure here */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir(quot;/quot;)) < 0) {
/* Log any failure here */
exit(EXIT_FAILURE);
}
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
It’s a good idea to stick with the constants defined for the file descriptors, for the greatest portability between
system versions.
5 Writing the Daemon Code
5.1 Initialization
At this point, you have basically told Linux that you’re a daemon, so now it’s time to write the actual
daemon code. Initialization is the first step here. Since there can be a multitude of different functions that
can be called here to set up your daemon’s task, I won’t go too deep into them here.
The big point here is, when initializing anything in a daemon, the same defensive coding guidelines apply.
Be as verbose as possible when writing either to the syslog or your own logs. Debugging a daemon can be
quite difficult when there isn’t enough information available as to the status of the daemon.
5.2 The Big Loop
A daemon’s main code is typically inside an infinite loop. Technically, it isn’t an infinite loop, but it is
structured as one:
pid_t pid, sid;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
7. 6. Putting It All Together 7
}
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log any failures here */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir(quot;/quot;)) < 0) {
/* Log any failures here */
exit(EXIT_FAILURE);
}
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Daemon-specific initialization goes here */
/* The Big Loop */
while (1) {
/* Do some task here ... */
sleep(30); /* wait 30 seconds */
}
This typical loop is usually a while loop that has an infinite terminating condition, with a call to sleep in
there to make it run at specified intervals.
Think of it like a heartbeat: when your heart beats, it performs a few tasks, then waits until the next beat
takes place. Many daemons follow this same methodology.
6 Putting It All Together
6.1 Complete Sample
Listed below is a complete sample daemon that shows all of the steps necessary for setup and execution. To
run this, simply compile using gcc, and start execution from the command line. To terminate, use the kill
command after finding its PID.
I’ve also put in the include statements for interfacing with the syslog, recommended (at the very
8. 6. Putting It All Together 8
least) for sending start/stop/pause/die log statements, in addition to using your own logs with the
fopen()/fwrite()/fclose() function calls.
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
int main(void) {
/* Our process ID and Session ID */
pid_t pid, sid;
/* 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);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir(quot;/quot;)) < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Daemon-specific initialization goes here */
/* The Big Loop */
9. 6. Putting It All Together 9
while (1) {
/* Do some task here ... */
sleep(30); /* wait 30 seconds */
}
exit(EXIT_SUCCESS);
}
From here, you should be able to use this skeleton to write your own daemons. Be sure to add in your own
logging (or use the syslog facility). Finally, code defensively, code defensively, code defensively!