user3455075
user3455075

Reputation: 9

create a daemon in c that runs in the background but does not perform its task until I request it to

I need to create a daemon in c that runs in the background but does not perform its task until I request it to.

Just for an example; I have created a daemon that when run will perform a

du -h --max depth=3

command on /home and output it to a file. However I want the daemon to run in the background and not perform this task until I request it.

I’ll admit this sounds pointless but I have set of programs that I want to combine into one daemon that performs tasks upon request.

Any advice or example on this are greatly appreciated.

Many Thanks,

Upvotes: 1

Views: 703

Answers (2)

Darpan
Darpan

Reputation: 115

"However I want the daemon to run in the background and not perform this task until I request it. "

One possible Solution:

When you fork the process to create a child process, write its PID (PID of the child) to a file. This will be helpful to use signalling for your daemon process. You can use SIGUSR1 to perform your task. Write a signal handler for SIGUSR1 in your daemon process to do the task which you are talking about. In order to control your task or start a task when you request it, you have to just send a signal (SIGUSR1 in this case) to daemon. When the daemon receives this signal, it will execute its signal handler which would be the task you have defined for execution. Until you send this signal, the task will not be executed.

The signal can be sent like this:

kill(PID, SIGUSR1) // Read the PID of daemon from the file (which you had earlier written into, after forking)

Thus your main process can read the PID from the file, and send the signal to daemon which will then start the execution of specified task.

For anyone, who finds this useful

Upvotes: 0

GNSL
GNSL

Reputation: 111

If you are writing it in C and you are on a unix system, use the daemon() libc call to fork the daemon. It will take care of all of the nitty details that go into properly deamonizing your process.

To wait for an event, choose any type of inter process communication you want and read a message from that mechanism using a blocking read. For example your daemon could wait for a message to be received over a named pipe.

If you need to wait on multiple event sources, you can take advantage of asynchronous programming using select or poll or epoll.

If you want to perform an action at some interval use timer_fd.

Upvotes: 2

Related Questions