I am working on an embedded linux with busybox. As part of my application I have a rc.init script E80-startmyprog. That script is calling my program prog.
trap "" HUP
startmyprog >${LOGFILE} 2>&1 </dev/null &
startmyprog() {
prog
}
In my program I can see that the signal handlers are set to ignore SIGHUP. I am checking that with
struct sigaction act;
sigaction(1, NULL, &act);
printf("action %p\n", act.sa_sigaction); // prints out 1 -> SIG_IGN
Now at some time in my program I need to start another process, give it some input and check if it printed "yes" on stdout. I am using system to do that.
const int ret = system("[ `echo input | second_process` == yes ]");
Normal behavior is that WIFEXITED(ret) is true and that WEXITSTATUS(ret) is 0 or 1.
But in some cases with unfortunate timing WIFSIGNALED(ret) is true and WTERMSIG(ret) is 1 (SIGHUP).
Debugging shows that if I execl("second_process", "second_process", (char*)NULL) the signal handler state in second_process is set correctly to SIGHUP=ignore. But if I use system, then second_process has SIGHUP=default.
My questions are:
What is going on there? Who is resetting the SIGHUP signal handler at startup? Is it the shell? Is there a way to prevent that? (In the sh man page I have not seen a command line option that looks so.)
I know I could do a workaround and setup a pipe, fork, exec second_process, write input to pipe, read output from pipe and parse output, but that is a lot of stuff compared to a system one liner and there is good chance that I will miss something and get it wrong.
I don't think that's exactly what's happening. When you type 'trap' into the shell, you're asking it list the actions it has established for that signal. When you invoke a subshell, you haven't given it any actions, so it won't show any (it doesn't know about what you gave to its parent) but that doesn't mean it has reset the SIGHUP state.
Try this small script that proves SIGHUP is still ignored even though "trap" shows nothing:
trap "" HUP
echo "TRAPs in parent"
trap
sh -c 'echo "TRAPs in child"; trap; sleep 5; echo "Still here. Traps: "; trap' &
child=$!
sleep 1
kill -HUP $child
echo 'Killed child'
Digging deeper into the sources of the busybox that is running on the Linux I found out that the shell in busybox is calling signal(SIGHUP, SIG_DFL); during init. This resets the sighup handler to default. So the shell itself and the program it runs (provided with -c ...) are running with default SIGHUP handler.
I see no code path that bypasses resetting the SIGHUP signal handler, so it seems I cannot achieve what I want with system().
I have a C program running (in terminal)
My program has a loop(while(1){}, for example),
So if I want to stop it, I have to press ctrl + C
My question:
Is there any way to run a last function in my C program when I press Ctrl+C?
For example I typed Ctrl+C in my linux terminal an then my program detects that I typed Ctrl+C and it prints something like "bye bye" or open a file, etc.
Hope, you understood me.
Thanks in advance.
You need to use signal call to install a handler for the SIGINT signal.
when you press ctrl+c a signal SIGINT is generated. so you need to write a function to catch that signal. for that you can write a function say,
void catch_signal_ctrlC(int s)
{
//...
printf("Bye");
}
then to catch signal register as,
signal(SIGINT, catch_signal_ctrlC)
this system call will register catch_signal_ctrlC() function to catch SIGINT i.e. it will be called whenever you press ctrl+c in terminal
I have a program that requires it to pause and resume another program. To do this, I use the kill function, either from code with: -
kill(pid, SIGSTOP); // to pause
kill(pid, SIGCONT); // to resume
Or from the command line with the similar
kill -STOP <pid>
kill -CONT <pid>
I can trace what's going on with the threads using this code, taken from Mac OS X Internals.
If a program is paused and immediately resumed, the state of threads can show as UNINTERRUPTIBLE. Most of the time, they report as WAITING, which is not surprising and if a thread is doing work, it will show as RUNNING.
What I don't understand is when I pause a program and view the states of the threads, they still show as WAITING. I would have expected their state to be either STOPPED or HALTED
Can someone explain why they still show as WAITING and when would they be STOPPED or HALTED. In addition, is there another structure somewhere that shows the state of the program and its threads being halted in this way?
"Waiting" is shown in your case because you did not terminate the program rather paused it, where as Stopped or Halted state usually occurs when the program immediately stopped working due to some runtime error. As far as your second question is concerned, I do not think there is some other structure out there to show the state of the program. Cheers
After researching and experimenting with the available structures, I've discovered that it is possible to show the state of a program being halted by looking at the process suspend count. This is my solution: -
int ProcessIsSuspended(unsigned int pid)
{
kern_return_t kr;
mach_port_t task;
mach_port_t mytask;
mytask = mach_task_self();
kr = task_for_pid(mytask, pid, &task);
// handle error here...
char infoBuf[TASK_INFO_MAX];
struct task_basic_info_64 *tbi;
int infoSize = TASK_INFO_MAX;
kr = task_info(task, TASK_BASIC_INFO_64, (task_info_t)infoBuf, (mach_msg_type_number_t *)&infoSize);
// handle error here....
tbi = (struct task_basic_info_64 *) infoBuf;
if(tbi->suspend_count > 0) // process is suspended
return 1;
return 0;
}
If suspend_count is 0, the program is running, else it is in a paused state, waiting to be resumed.
In Linux I want to add a daemon that cannot be stopped and which monitors filesystem changes.
If any changes are detected, it should write the path to the console where it was started plus a newline.
I already have the filesystem changing code almost ready but I cannot figure out how to create a daemon.
My code is from here: http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
What to do after the fork?
int main (int argc, char **argv) {
pid_t pID = fork();
if (pID == 0) { // child
// Code only executed by child process
sIdentifier = "Child Process: ";
}
else if (pID < 0) {
cerr << "Failed to fork" << endl;
exit(1);
// Throw exception
}
else // parent
{
// Code only executed by parent process
sIdentifier = "Parent Process:";
}
return 0;
}
In Linux i want to add a daemon that cannot be stopped and which monitors filesystem changes. If any changes would be detected it should write the path to the console where it was started + a newline.
Daemons work in the background and (usually...) don't belong to a TTY that's why you can't use stdout/stderr in the way you probably want.
Usually a syslog daemon (syslogd) is used for logging messages to files (debug, error,...).
Besides that, there are a few required steps to daemonize a process.
If I remember correctly these steps are:
fork off the parent process & let it terminate if forking was successful. -> Because the parent process has terminated, the child process now runs in the background.
setsid - Create a new session. The calling process becomes the leader of the new session and the process group leader of the new process group. The process is now detached from its controlling terminal (CTTY).
Catch signals - Ignore and/or handle signals.
fork again & let the parent process terminate to ensure that you get rid of the session leading process. (Only session leaders may get a TTY again.)
chdir - Change the working directory of the daemon.
umask - Change the file mode mask according to the needs of the daemon.
close - Close all open file descriptors that may be inherited from the parent process.
To give you a starting point: Look at this skeleton code that shows the basic steps. This code can now also be forked on GitHub: Basic skeleton of a linux daemon
/*
* daemonize.c
* This example daemonizes a process, writes a few log messages,
* sleeps 20 seconds and terminates afterwards.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
static void skeleton_daemon()
{
pid_t pid;
/* Fork off the parent process */
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* On success: The child process becomes session leader */
if (setsid() < 0)
exit(EXIT_FAILURE);
/* Catch, ignore and handle signals */
//TODO: Implement a working signal handler */
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
/* Fork off for the second time*/
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* Set new file permissions */
umask(0);
/* Change the working directory to the root directory */
/* or another appropriated directory */
chdir("/");
/* Close all open file descriptors */
int x;
for (x = sysconf(_SC_OPEN_MAX); x>=0; x--)
{
close (x);
}
/* Open the log file */
openlog ("firstdaemon", LOG_PID, LOG_DAEMON);
}
int main()
{
skeleton_daemon();
while (1)
{
//TODO: Insert daemon code here.
syslog (LOG_NOTICE, "First daemon started.");
sleep (20);
break;
}
syslog (LOG_NOTICE, "First daemon terminated.");
closelog();
return EXIT_SUCCESS;
}
Compile the code: gcc -o firstdaemon daemonize.c
Start the daemon: ./firstdaemon
Check if everything is working properly: ps -xj | grep firstdaemon
The output should be similar to this one:
+------+------+------+------+-----+-------+------+------+------+-----+
| PPID | PID | PGID | SID | TTY | TPGID | STAT | UID | TIME | CMD |
+------+------+------+------+-----+-------+------+------+------+-----+
| 1 | 3387 | 3386 | 3386 | ? | -1 | S | 1000 | 0:00 | ./ |
+------+------+------+------+-----+-------+------+------+------+-----+
What you should see here is:
The daemon has no controlling terminal (TTY = ?)
The parent process ID (PPID) is 1 (The init process)
The PID != SID which means that our process is NOT the session leader
(because of the second fork())
Because PID != SID our process can't take control of a TTY again
Reading the syslog:
Locate your syslog file. Mine is here: /var/log/syslog
Do a: grep firstdaemon /var/log/syslog
The output should be similar to this one:
firstdaemon[3387]: First daemon started.
firstdaemon[3387]: First daemon terminated.
A note:
In reality you would also want to implement a signal handler and set up the logging properly (Files, log levels...).
Further reading:
Linux-UNIX-Programmierung - German
Unix Daemon Server Programming
man 7 daemon describes how to create daemon in great detail. My answer is just excerpt from this manual.
There are at least two types of daemons:
traditional SysV daemons (old-style),
systemd daemons (new-style).
SysV Daemons
If you are interested in traditional SysV daemon, you should implement the following steps:
Close all open file descriptors except standard input, output, and error (i.e. the first three file descriptors 0, 1, 2). This ensures that no accidentally passed file descriptor stays around in the daemon process. On Linux, this is best implemented by iterating through /proc/self/fd, with a fallback of iterating from file descriptor 3 to the value returned by getrlimit() for RLIMIT_NOFILE.
Reset all signal handlers to their default. This is best done by iterating through the available signals up to the limit of _NSIG and resetting them to SIG_DFL.
Reset the signal mask using sigprocmask().
Sanitize the environment block, removing or resetting environment variables that might negatively impact daemon runtime.
Call fork(), to create a background process.
In the child, call setsid() to detach from any terminal and create an independent session.
In the child, call fork() again, to ensure that the daemon can never re-acquire a terminal again.
Call exit() in the first child, so that only the second child (the actual daemon process) stays around. This ensures that the daemon process is re-parented to init/PID 1, as all daemons should be.
In the daemon process, connect /dev/null to standard input, output, and error.
In the daemon process, reset the umask to 0, so that the file modes passed to open(), mkdir() and suchlike directly control the access mode of the created files and directories.
In the daemon process, change the current directory to the root directory (/), in order to avoid that the daemon involuntarily blocks mount points from being unmounted.
In the daemon process, write the daemon PID (as returned by getpid()) to a PID file, for example /run/foobar.pid (for a hypothetical daemon "foobar") to ensure that the daemon cannot be started more than once. This must be implemented in race-free fashion so that the PID file is only updated when it is verified at the same time that the PID previously stored in the PID file no longer exists or belongs to a foreign process.
In the daemon process, drop privileges, if possible and applicable.
From the daemon process, notify the original process started that initialization is complete. This can be implemented via an unnamed pipe or similar communication channel that is created before the first fork() and hence available in both the original and the daemon process.
Call exit() in the original process. The process that invoked the daemon must be able to rely on that this exit() happens after initialization is complete and all external communication channels are established and accessible.
Note this warning:
The BSD daemon() function should not be used, as it implements only a subset of these steps.
A daemon that needs to provide compatibility with SysV systems should implement the scheme pointed out above. However, it is recommended to make this behavior optional and configurable via a command line argument to ease debugging as well as to simplify integration into systems using systemd.
Note that daemon() is not POSIX compliant.
New-Style Daemons
For new-style daemons the following steps are recommended:
If SIGTERM is received, shut down the daemon and exit cleanly.
If SIGHUP is received, reload the configuration files, if this applies.
Provide a correct exit code from the main daemon process, as this is used by the init system to detect service errors and problems. It is recommended to follow the exit code scheme as defined in the LSB recommendations for SysV init scripts.
If possible and applicable, expose the daemon's control interface via the D-Bus IPC system and grab a bus name as last step of initialization.
For integration in systemd, provide a .service unit file that carries information about starting, stopping and otherwise maintaining the daemon. See systemd.service(5) for details.
As much as possible, rely on the init system's functionality to limit the access of the daemon to files, services and other resources, i.e. in the case of systemd, rely on systemd's resource limit control instead of implementing your own, rely on systemd's privilege dropping code instead of implementing it in the daemon, and similar. See systemd.exec(5) for the available controls.
If D-Bus is used, make your daemon bus-activatable by supplying a D-Bus service activation configuration file. This has multiple advantages: your daemon may be started lazily on-demand; it may be started in parallel to other daemons requiring it — which maximizes parallelization and boot-up speed; your daemon can be restarted on failure without losing any bus requests, as the bus queues requests for activatable services. See below for details.
If your daemon provides services to other local processes or remote clients via a socket, it should be made socket-activatable following the scheme pointed out below. Like D-Bus activation, this enables on-demand starting of services as well as it allows improved parallelization of service start-up. Also, for state-less protocols (such as syslog, DNS), a daemon implementing socket-based activation can be restarted without losing a single request. See below for details.
If applicable, a daemon should notify the init system about startup completion or status updates via the sd_notify(3) interface.
Instead of using the syslog() call to log directly to the system syslog service, a new-style daemon may choose to simply log to standard error via fprintf(), which is then forwarded to syslog by the init system. If log levels are necessary, these can be encoded by prefixing individual log lines with strings like "<4>" (for log level 4 "WARNING" in the syslog priority scheme), following a similar style as the Linux kernel's printk() level system. For details, see sd-daemon(3) and systemd.exec(5).
To learn more read whole man 7 daemon.
You cannot create a process in linux that cannot be killed. The root user (uid=0) can send a signal to a process, and there are two signals which cannot be caught, SIGKILL=9, SIGSTOP=19. And other signals (when uncaught) can also result in process termination.
You may want a more general daemonize function, where you can specify a name for your program/daemon, and a path to run your program (perhaps "/" or "/tmp"). You may also want to provide file(s) for stderr and stdout (and possibly a control path using stdin).
Here are the necessary includes:
#include <stdio.h> //printf(3)
#include <stdlib.h> //exit(3)
#include <unistd.h> //fork(3), chdir(3), sysconf(3)
#include <signal.h> //signal(3)
#include <sys/stat.h> //umask(3)
#include <syslog.h> //syslog(3), openlog(3), closelog(3)
And here is a more general function,
int
daemonize(char* name, char* path, char* outfile, char* errfile, char* infile )
{
if(!path) { path="/"; }
if(!name) { name="medaemon"; }
if(!infile) { infile="/dev/null"; }
if(!outfile) { outfile="/dev/null"; }
if(!errfile) { errfile="/dev/null"; }
//printf("%s %s %s %s\n",name,path,outfile,infile);
pid_t child;
//fork, detach from process group leader
if( (child=fork())<0 ) { //failed fork
fprintf(stderr,"error: failed fork\n");
exit(EXIT_FAILURE);
}
if (child>0) { //parent
exit(EXIT_SUCCESS);
}
if( setsid()<0 ) { //failed to become session leader
fprintf(stderr,"error: failed setsid\n");
exit(EXIT_FAILURE);
}
//catch/ignore signals
signal(SIGCHLD,SIG_IGN);
signal(SIGHUP,SIG_IGN);
//fork second time
if ( (child=fork())<0) { //failed fork
fprintf(stderr,"error: failed fork\n");
exit(EXIT_FAILURE);
}
if( child>0 ) { //parent
exit(EXIT_SUCCESS);
}
//new file permissions
umask(0);
//change to path directory
chdir(path);
//Close all open file descriptors
int fd;
for( fd=sysconf(_SC_OPEN_MAX); fd>0; --fd )
{
close(fd);
}
//reopen stdin, stdout, stderr
stdin=fopen(infile,"r"); //fd=0
stdout=fopen(outfile,"w+"); //fd=1
stderr=fopen(errfile,"w+"); //fd=2
//open syslog
openlog(name,LOG_PID,LOG_DAEMON);
return(0);
}
Here is a sample program, which becomes a daemon, hangs around, and then leaves.
int
main()
{
int res;
int ttl=120;
int delay=5;
if( (res=daemonize("mydaemon","/tmp",NULL,NULL,NULL)) != 0 ) {
fprintf(stderr,"error: daemonize failed\n");
exit(EXIT_FAILURE);
}
while( ttl>0 ) {
//daemon code here
syslog(LOG_NOTICE,"daemon ttl %d",ttl);
sleep(delay);
ttl-=delay;
}
syslog(LOG_NOTICE,"daemon ttl expired");
closelog();
return(EXIT_SUCCESS);
}
Note that SIG_IGN indicates to catch and ignore the signal. You could build a signal handler that can log signal receipt, and set flags (such as a flag to indicate graceful shutdown).
Try using the daemon function:
#include <unistd.h>
int daemon(int nochdir, int noclose);
From the man page:
The daemon() function is for programs wishing to detach themselves
from the controlling terminal and run in the background as system
daemons.
If nochdir is zero, daemon() changes the calling process's current
working directory to the root directory ("/"); otherwise, the current
working directory is left unchanged.
If noclose is zero, daemon() redirects standard input, standard
output and standard error to /dev/null; otherwise, no changes are
made to these file descriptors.
I can stop at the first requirement "A daemon which cannot be stopped ..."
Not possible my friend; however, you can achieve the same with a much better tool, a kernel module.
http://www.infoq.com/articles/inotify-linux-file-system-event-monitoring
All daemons can be stopped. Some are more easily stopped than others. Even a daemon pair with the partner in hold down, respawning the partner if lost, can be stopped. You just have to work a little harder at it.
If your app is one of:
{
".sh": "bash",
".py": "python",
".rb": "ruby",
".coffee" : "coffee",
".php": "php",
".pl" : "perl",
".js" : "node"
}
and you don't mind a NodeJS dependency then install NodeJS and then:
npm install -g pm2
pm2 start yourapp.yourext --name "fred" # where .yourext is one of the above
pm2 start yourapp.yourext -i 0 --name "fred" # run your app on all cores
pm2 list
To keep all apps running on reboot (and daemonise pm2):
pm2 startup
pm2 save
Now you can:
service pm2 stop|restart|start|status
(also easily allows you to watch for code changes in your app directory and auto restart the app process when a code change happens)
Daemon Template
I wrote a daemon template following the new-style daemon: link
You can find the entire template code on GitHub: here
Main.cpp
// This function will be called when the daemon receive a SIGHUP signal.
void reload() {
LOG_INFO("Reload function called.");
}
int main(int argc, char **argv) {
// The Daemon class is a singleton to avoid be instantiate more than once
Daemon& daemon = Daemon::instance();
// Set the reload function to be called in case of receiving a SIGHUP signal
daemon.setReloadFunction(reload);
// Daemon main loop
int count = 0;
while(daemon.IsRunning()) {
LOG_DEBUG("Count: ", count++);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
LOG_INFO("The daemon process ended gracefully.");
}
Daemon.hpp
class Daemon {
public:
static Daemon& instance() {
static Daemon instance;
return instance;
}
void setReloadFunction(std::function<void()> func);
bool IsRunning();
private:
std::function<void()> m_reloadFunc;
bool m_isRunning;
bool m_reload;
Daemon();
Daemon(Daemon const&) = delete;
void operator=(Daemon const&) = delete;
void Reload();
static void signalHandler(int signal);
};
Daemon.cpp
Daemon::Daemon() {
m_isRunning = true;
m_reload = false;
signal(SIGINT, Daemon::signalHandler);
signal(SIGTERM, Daemon::signalHandler);
signal(SIGHUP, Daemon::signalHandler);
}
void Daemon::setReloadFunction(std::function<void()> func) {
m_reloadFunc = func;
}
bool Daemon::IsRunning() {
if (m_reload) {
m_reload = false;
m_reloadFunc();
}
return m_isRunning;
}
void Daemon::signalHandler(int signal) {
LOG_INFO("Interrup signal number [", signal,"] recived.");
switch(signal) {
case SIGINT:
case SIGTERM: {
Daemon::instance().m_isRunning = false;
break;
}
case SIGHUP: {
Daemon::instance().m_reload = true;
break;
}
}
}
daemon-template.service
[Unit]
Description=Simple daemon template
After=network.taget
[Service]
Type=simple
ExecStart=/usr/bin/daemon-template --conf_file /etc/daemon-template/daemon-tenplate.conf
ExecReload=/bin/kill -HUP $MAINPID
User=root
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=daemon-template
[Install]
WantedBy=multi-user.target
By calling fork() you've created a child process. If the fork is successful (fork returned a non-zero PID) execution will continue from this point from within the child process. In this case we want to gracefully exit the parent process and then continue our work in the child process.
Maybe this will help:
http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html
A daemon is just a process in the background. If you want to start your program when the OS boots, on linux, you add your start command to /etc/rc.d/rc.local (run after all other scripts) or /etc/startup.sh
On windows, you make a service, register the service, and then set it to start automatically at boot in administration -> services panel.