Skip to content

Commit df46e63

Browse files
author
Rainer Keller
committed
Add detach option
This option allows to start applications using the regular appcontroller startup but does not block the caller until the application finishes. Change-Id: I954ecd58660f216f41597b04e8a4a01ca43d3d61 Reviewed-by: Christian Kandeler <[email protected]> Reviewed-by: Eirik Aavitsland <[email protected]>
1 parent 86a3dc9 commit df46e63

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

main.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
#include <sys/un.h>
3030
#include <unistd.h>
3131
#include <fcntl.h>
32+
#include <signal.h>
33+
#include <sys/wait.h>
3234

3335
#define PID_FILE "/data/user/.appcontroller"
3436

@@ -224,6 +226,7 @@ int main(int argc, char **argv)
224226
bool useGDB = false;
225227
bool useQML = false;
226228
bool fireAndForget = false;
229+
bool detach = false;
227230
Utils::PortList range;
228231

229232
if (args.isEmpty()) {
@@ -280,6 +283,8 @@ int main(int argc, char **argv)
280283
} else if (arg == "--version") {
281284
printf("Appcontroller version: " GIT_VERSION "\nGit revision: " GIT_HASH "\n");
282285
return 0;
286+
} else if (arg == "--detach") {
287+
detach = true;
283288
} else {
284289
args.prepend(arg);
285290
break;
@@ -296,6 +301,11 @@ int main(int argc, char **argv)
296301
return 1;
297302
}
298303

304+
if (detach && (useGDB || useQML)) {
305+
fprintf(stderr, "Detached debugging not possible. --detach and one of --useGDB, --useQML must not be used together.\n");
306+
return 1;
307+
}
308+
299309
if (useGDB) {
300310
int port = findFirstFreePort(range);
301311
if (port < 0) {
@@ -331,6 +341,38 @@ int main(int argc, char **argv)
331341
return 1;
332342
}
333343

344+
// daemonize
345+
if (detach) {
346+
pid_t rc = fork();
347+
if (rc == -1) {
348+
printf("fork failed\n");
349+
return -1;
350+
} else if (rc > 0) {
351+
// parent
352+
::wait(NULL); // wait for the child to exit
353+
return 0;
354+
}
355+
356+
setsid();
357+
chdir("/");
358+
signal(SIGHUP, SIG_IGN);
359+
360+
// child
361+
int devnull = open("/dev/null", O_RDWR);
362+
if (devnull < 0)
363+
return -1;
364+
dup2(devnull, 0); // Replace file descriptors
365+
dup2(devnull, 1);
366+
dup2(devnull, 2);
367+
rc = fork();
368+
if (rc == -1)
369+
return -1;
370+
else if (rc > 0)
371+
return 0;
372+
373+
// child
374+
}
375+
334376
// Create QCoreApplication after parameter parsing to prevent printing evaluation
335377
// message to terminal before QtCreator has parsed the output.
336378
QCoreApplication app(argc, argv);

0 commit comments

Comments
 (0)