Reputation: 151
I'm trying to create a background program that has main config file which contains another config file locations and execute each of them. For example: if main_config.conf:
/home/conf1
/home/conf2
i want to execute ./background_pro /home/conf1
and ./background_pro /home/conf2
in background. How do i do that ? I'm using below structure.Thank you
#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("/")) < 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 */
while (1) {
/* Do some task here ... */
sleep(30); /* wait 30 seconds */
}
exit(EXIT_SUCCESS);
}
Upvotes: 0
Views: 482
Reputation: 211
Just append an '&' at the rear of shell command, then the command will run in background. I think, this may be what you want: daemon.bash
#!bash
# to stop a sub process
if [ "x$1" = "x-stop" ]; then
if [ "x$2" = "xsub1" ]; then
kill `cat sub1.pid`
elif [ "x$2" = "xsub2" ]; then
kill `cat sub2.pid`
fi
exit
fi
# to start sub processes
conf1=`head -1 main_config.conf`
conf2=`head -2 main_config.conf | tail -1`
nohup ./background_pro $conf1 &
pid1=$!
echo "$pid1" > sub1.pid
nohup ./background_pro $conf2 &
pid2=$!
echo "$pid2" > sub2.pid
Run the demon:
nohup ./daemon.bash &
The nohup
will keep the program running even you turn off the terminal.
Stop sub process 1:
./daemon.bash -stop sub1
Upvotes: 1
Reputation: 354
A background program might be what linux users call a "Daemon" program. Please look here on Creating a daemon in Linux where you can find a plethora of information on how to begin writing your own Daemon. For parsing command line arguments, i recommend reading the GNU c library manual for getopt().
Upvotes: 0