Skip to content

Commit

Permalink
Fix deamon mode on macos
Browse files Browse the repository at this point in the history
  • Loading branch information
CamilleScholtz authored and MaxKellermann committed Feb 1, 2025
1 parent 407db96 commit e3cf9bb
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 0 deletions.
6 changes: 6 additions & 0 deletions meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,12 @@ if is_windows
]
endif

if is_darwin
sources += [
'src/apple/AppleMain.cxx',
]
endif

if not is_android
sources += [
'src/CommandLine.cxx',
Expand Down
2 changes: 2 additions & 0 deletions src/Main.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,8 @@ try {

#ifdef _WIN32
return win32_main(argc, argv);
#elif __APPLE__
return apple_main(argc, argv);
#else
return mpd_main(argc, argv);
#endif
Expand Down
12 changes: 12 additions & 0 deletions src/Main.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,16 @@ win32_app_stopping();

#endif

#ifdef __APPLE__

/**
* If program is run as deamon on macos, fork very early to avoid objc runtime issues,
* and then calls mpd_main() with specified arguments.
* If program is run as a regular application calls mpd_main() immediately.
*/
int
apple_main(int argc, char *argv[]);

#endif

#endif
38 changes: 38 additions & 0 deletions src/apple/AppleMain.cxx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright The Music Player Daemon Project

#include "Main.hxx"
#include "Instance.hxx"
#include "CommandLine.hxx"
#include "net/Init.hxx"
#include "config/Data.hxx"

static int service_argc;
static char **service_argv;

int apple_main(int argc, char *argv[])
{
service_argc = argc;
service_argv = argv;

#ifdef ENABLE_DAEMON
CommandLineOptions options;
ConfigData raw_config;

ParseCommandLine(argc, argv, options, raw_config);

if (options.daemon) {
// Fork before any Objective-C runtime initializations
pid_t pid = fork();
if (pid < 0)
throw MakeErrno("fork() failed");

if (pid > 0) {
// Parent process: exit immediately
_exit(0);
}
}
#endif

return mpd_main(argc, argv);
}
4 changes: 4 additions & 0 deletions src/unix/Daemon.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ daemonize_begin(bool detach)

/* move to a child process */

#ifndef __APPLE__

pid_t pid = fork();
if (pid < 0)
throw MakeErrno("fork() failed");
Expand Down Expand Up @@ -178,6 +180,8 @@ daemonize_begin(bool detach)
WCOREDUMP(status) ? " (core dumped)" : "");

std::exit(WEXITSTATUS(status));

#endif
}

void
Expand Down

0 comments on commit e3cf9bb

Please sign in to comment.