Mam demon samodzielny bez nohup,
wołam "program 12"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <thread>
#include <unistd.h>
#include <fcntl.h>
using namespace std;
int main(int argc, char * argv[])
{
char cwd[1024];
string sCWD;
if (getcwd(cwd, sizeof(cwd)) != NULL)
sCWD = cwd; else sCWD = "/";
if (sCWD.back()!='/') sCWD+="/";
const int autorestart = 5;
if (argc < 2)
exit(1);
int numsec = atoi(argv[1]);
if (numsec==0) exit(1);
ofstream file;
file.open(sCWD+"stdout.out"+to_string(numsec),ios::out);
file.close();
file.open(sCWD+"stderr.out"+to_string(numsec),ios::out);
file.close();
int pid = fork();
if (pid < 0)
exit(1); // fork failed
if (pid > 0)
exit(0); // still in parent process, so quit
// in child process, obtain new session and process group at the same time
setsid();
{
int devnull = open("/dev/null", O_RDWR);
int stdoutfile = open((sCWD+"stdout.out"+to_string(numsec)).c_str(), O_WRONLY );
int stderrfile = open((sCWD+"stderr.out"+to_string(numsec)).c_str(), O_WRONLY );
// close stdin stdout and stderr which are connected to current terminal
close(0);
close(1);
close(2);
// attach stdin stdout and stderr to /dev/null
// by dup-ing the devnull descriptor
dup2(devnull, 0);
dup2(stdoutfile, 1);
dup2(stderrfile, 2);
// get rid of devnull
close(devnull);
close(stdoutfile);
close(stderrfile);
}
printf("numsec=%d\n",numsec);
for (int i=0; i<min(autorestart,numsec); i++)
{
this_thread::sleep_for(chrono::seconds(1));
printf("%d\n",i);
}
if (numsec<=autorestart) exit(0);
execl(argv[0],argv[0],to_string(numsec - autorestart).c_str(),NULL);
return 0;
}