when we use raise in GCD, the signal handler is executed asynchronously, whereas in pthread, it is executed synchronously as expected.
example:
#include <Foundation/Foundation.h>
#include <pthread/pthread.h>
static void HandleSignal(int sigNum, siginfo_t* signalInfo, void* userContext) {
printf("handle signal %d\n", sigNum);
printf("begin sleep\n");
sleep(3);
printf("end sleep\n");
}
void InstallSignal(void) {
static const int g_fatalSignals[] =
{
SIGABRT,
SIGBUS,
SIGFPE,
SIGILL,
SIGPIPE,
SIGSEGV,
SIGSYS,
SIGTRAP,
};
int fatalSignalsCount = sizeof(g_fatalSignals) / sizeof(int);
struct sigaction action = {{0}};
action.sa_flags = SA_SIGINFO | SA_ONSTACK;
#if defined(__LP64__)
action.sa_flags |= SA_64REGSET;
#endif
sigemptyset(&action.sa_mask);
action.sa_sigaction = &HandleSignal;
struct sigaction pre_sa;
for(int i = 0; i < fatalSignalsCount; i++) {
int sigResult = sigaction(g_fatalSignals[i], &action, &pre_sa);
}
}
void* RaiseAbort(void *userdata) {
raise(SIGABRT);
printf("signal handler has finished\n");
return NULL;
}
int main(int argc, const char * argv[]) {
InstallSignal();
dispatch_async(dispatch_get_global_queue(0, 0), ^{
raise(SIGABRT);
// abort(); // abort() is ok
RaiseAbort(nullptr);
});
// pthread is ok
// pthread_t tid;
// int ret = pthread_create(&tid, NULL, RaiseAbort, NULL);
// if (ret != 0) {
// fprintf(stderr, "create thread failed\n");
// return EXIT_FAILURE;
// }
[[NSRunLoop mainRunLoop] run];
return 0;
}
console log:
signal handler has finished
handle signal 6
begin sleep
end sleep
Processes & Concurrency
RSS for tagDiscover how the operating system manages multiple applications and processes simultaneously, ensuring smooth multitasking performance.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
General:
Forums subtopic: App & System Services > Processes & Concurrency
Forums tag: Background Tasks
Background Tasks framework documentation
UIApplication background tasks documentation
ProcessInfo expiring activity documentation
Using background tasks documentation for watchOS
Performing long-running tasks on iOS and iPadOS documentation
WWDC 2020 Session 10063 Background execution demystified — This is critical resource. Watch it! [1]
WWDC 2022 Session 10142 Efficiency awaits: Background tasks in SwiftUI
iOS Background Execution Limits forums post
UIApplication Background Task Notes forums post
Testing and Debugging Code Running in the Background forums post
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] Sadly the video is currently not available from Apple. I’ve left the link in place just in case it comes back.
https://developer.apple.com/forums/thread/708877
XPC is the preferred inter-process communication (IPC) mechanism on Apple platforms. XPC has three APIs:
The high-level NSXPCConnection API, for Objective-C and Swift
The low-level Swift API, introduced with macOS 14
The low-level C API, which, while callable from all languages, works best with C-based languages
General:
Forums subtopic: App & System Services > Processes & Concurrency
Forums tag: XPC
Creating XPC services documentation
NSXPCConnection class documentation
Low-level API documentation
XPC has extensive man pages — For the low-level API, start with the xpc man page; this is the original source for the XPC C API documentation and still contains titbits that you can’t find elsewhere. Also read the xpcservice.plist man page, which documents the property list format used by XPC services.
Daemons and Services Programming Guide archived documentation
WWDC 2012 Session 241 Cocoa Interprocess Communication with XPC — This is no longer available from the Apple Developer website )-:
Technote 2083 Daemons and Agents — It hasn’t been updated in… well… decades, but it’s still remarkably relevant.
TN3113 Testing and Debugging XPC Code With an Anonymous Listener
XPC and App-to-App Communication forums post
Validating Signature Of XPC Process forums post
This forums post summarises the options for bidirectional communication
This forums post explains the meaning of privileged flag
Related tags include:
Inter-process communication, for other IPC mechanisms
Service Management, for installing and uninstalling Service Management login items, launchd agents, and launchd daemons
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
I have been experimenting with the BGContinuedProcessingTask API recently (and published sample code for it https://github.com/infinitepower18/BGContinuedProcessingTaskDemo)
I have noticed that if I lock the phone, the code that runs as part of the task stops executing. My sample code simply updates the progress each second until it gets to 100, so it should be completed in 1 minute 40 seconds. However, after locking the phone and checking the lock screen a few seconds later the progress indicator was in the same position as before I locked it.
If I leave the phone locked for several minutes and check the lock screen the live activity says "Task failed".
I haven't seen anything in the documentation regarding execution of tasks while the phone is locked. So I'm a bit confused if I encountered an iOS bug here?
I'm looking into a newer XPC API available starting with macOS 14. Although it's declared as a low-level API I can't figure it how to specify code signing requirement using XPCListener and XPCSession. How do I connect it with xpc_listener_set_peer_code_signing_requirement and xpc_connection_set_peer_code_signing_requirement which require xpc_listener_t and xpc_connection_t respectively?
Foundation XPC is declared as a high-level API and provides easy ways to specify code signing requirements on both ends of xpc.
I'm confused with all these XPC APIs and their future:
Newer really high-level XPCListener and XPCSession API (in low-level framework???)
Low-level xpc_listener_t & xpc_connection_t -like API. Is it being replaced by newer XPCListener and XPCSession?
How is it related to High-level Foundation XPC? Are NSXPCListener and NSXPCConnection going to be deprecated and replaced by XPCListener and XPCSession??
Hello,
I am trying to implement a subscriber which specifies its own demand for how many elements it wants to receive from a publisher.
My code is below:
import Combine
var array = [1, 2, 3, 4, 5, 6, 7]
struct ArraySubscriber<T>: Subscriber {
typealias Input = T
typealias Failure = Never
let combineIdentifier = CombineIdentifier()
func receive(subscription: any Subscription) {
subscription.request(.max(4))
}
func receive(_ input: T) -> Subscribers.Demand {
print("input,", input)
return .max(4)
}
func receive(completion: Subscribers.Completion<Never>) {
switch completion {
case .finished:
print("publisher finished normally")
case .failure(let failure):
print("publisher failed due to, ", failure)
}
}
}
let subscriber = ArraySubscriber<Int>()
array.publisher.subscribe(subscriber)
According to Apple's documentation, I specify the demand inside the receive(subscription: any Subscription) method, see link.
But when I run this code I get the following output:
input, 1
input, 2
input, 3
input, 4
input, 5
input, 6
input, 7
publisher finished normally
Instead, I expect the subscriber to only "receive" elements 1, 2, 3, 4 from the array.
How can I accomplish this?
The application is placed into the idle state. Subsequently, the device enters a sleep state.
While the device is in sleep, App start background task within the application successfully receives its expirationHandler callback.
App received the expiration callback and App called the end BGtask
OS did not released the Assertion.
Resulting in App getting terminated by the OS for exceeding the BG task
Apple Feedback- FB19192371
My app does really large uploads. Like several GB. We use the AWS SDK to upload to S3.
It seemed like using BGContinuedProcessingTask to complete a set of uploads for a particular item may improve UX as well as performance and reliability.
When I tried to get BGContinuedProcessingTask working with the AWS SDK I found that the task would fail after maybe 30 seconds. It looked like this was because the app stopped receiving updates from the AWS upload and the task wants consistent updates. The AWS SDK always uses a background URLSession and this is not configurable. I understand the background URLSession runs in a separate process from the app and maybe that is why progress updates did not continue when the app was in the background.
Is it expected that BGContinuedProcessingTask and background URLSession are not really compatible? It would not be shocking since they are 2 separate background APIs.
Would the Apple recommendation be to use a normal URLSession for this, in which case AWS would need to change their SDK?
Or does Apple think that BGContinuedProcessingTask should just not be used with uploads? In other words use an upload specific API.
Thanks!
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
iOS
Beta
Background Tasks
CFNetwork
I'm working on an enterprise product that's mainly a daemon (with Endpoint Security) without any GUI component. I'm looking into the update process for daemons/agents that was introduced with Ventura (Link), but I have to say that the entire process is just deeply unfun. Really can't stress this enough how unfun.
Anyway...
The product bundle now contains a dedicated Swift executable that calls SMAppService.register for both the daemon and agent.
It registers the app in the system preferences login items menu, but I also get an error.
Error registering daemon: Error Domain=SMAppServiceErrorDomain Code=1 "Operation not permitted" UserInfo={NSLocalizedFailureReason=Operation not permitted}
What could be the reason?
I wouldn't need to activate the items, I just need them to be added to the list, so that I can control them via launchctl.
Which leads me to my next question, how can I control bundled daemons/agents via launchctl? I tried to use launchctl enable and bootstrap, just like I do with daemons under /Library/LaunchDaemons, but all I get is
sudo launchctl enable system/com.identifier.daemon
sudo launchctl bootstrap /Path/to/daemon/launchdplist/inside/bundle/Library/LaunchDaemons/com.blub.plist
Bootstrap failed: 5: Input/output error (not super helpful error message)
I'm really frustrated by the complexity of this process and all of its pitfalls.
Every time macOS goes to sleep the processes get suspended which is expected. But during the sleep period, all processes keep coming back and they all get a small execution window where they make some n/w requests. Regardless of what power settings i have. It also does not matter whether my app is a daemon or not
Is there any way that i can disable this so that when system is in sleep, it stays in suspended, no intermittent execution window? I have tried disabling Wake for network access setting but processes still keep getting intermittent execution window.
Is there any way that i can prevent my app from coming back while in sleep. I don't want my app to get execution window, perform some executions and then get suspended not knowing when it will get execution window again?
Hello,
We're seeing some strange crashes and noticed the following. It's unclear if related or not.
The contract for xpc_main, which internally calls dispatch_main, is This function never returns. and they are appropriately peppered with __attribute__((__noreturn__)). Documentation states:
This function “parks” the main thread and waits for blocks to be submitted to the main queue.
However, internally, dispatch_main calls pthread_exit. pthread_exit's documentation states that:
After a thread has terminated, the result of access to local (auto)
variables of the thread is undefined. Thus, references to local
variables of the exiting thread should not be used for the
pthread_exit() value_ptr parameter value.
I'd say the two contracts of This function never returns. and thread exiting with its storage released are diametrically opposed and can create nuanced issues.
Consider the following code:
struct asd {
int a;
};
struct asd* ptr;
void fff(void* ctx)
{
while(true)
{
printf("%d\n", ptr->a);
ptr->a = (ptr->a + 1);
usleep(100000);
}
}
int main(int argc, const char * argv[]) {
struct asd zxc;
zxc.a = 1;
ptr = &zxc;
dispatch_async_f(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), NULL, fff);
dispatch_main();
return 0;
}
This is a ***** over-simplification of the code we have, but in the same "spirit". We have a C++ object that is created on the stack and exposes one of its members as a global pointer, with the assumption that it would never release. What I understand from This function never returns is that the calling thread remains dormant and its stack remains alive. What I understand from pthread_exit is that the thread is killed (this is verified with a debugger attached) and its stack storage is released.
Another thing that is throwing me off is that no sanitizer that is provided by clang/Xcode catches this issue. I don't see any special handling of the internal pthread_t in libdispatch to keep the stack storage alive.
Our code is more complex, but can be solved by allocating the initial object on the heap, rather than on the stack. But still I would like to understand if this is the expected behavior. Perhaps my preconception of __attribute__((__noreturn__)) is wrong, and accessing stack variables post call to a __attribute__((__noreturn__)) function is UB?
Thanks
Topic:
App & System Services
SubTopic:
Processes & Concurrency
I'm developing a safety-critical monitoring app that needs to fetch data from government APIs every 30 minutes and trigger emergency audio alerts for threshold violations.
The app must work reliably in background since users depend on it for safety alerts even while sleeping.
Main Challenge: iOS background limitations seem to prevent consistent 30-minute intervals. Standard BGTaskScheduler and timers get suspended after a few minutes in background.
Question: What's the most reliable approach to ensure consistent 30-minute background monitoring for a safety-critical app where missed alerts could have serious consequences?
Are there special entitlements or frameworks for emergency/safety applications?
The app needs to function like an alarm clock - working reliably even when backgrounded with emergency audio override capabilities.
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Network
AVAudioSession
Background Tasks
Hello,
I have a question regarding the behavior of BGProcessingTaskRequest when the app is force-quit by the user via the App Switcher.
Based on common understanding and various discussions — including the following Apple Developer Forum threads:
Waking up an iOS app after app is … | Apple Developer Forums
Will BGAppRefreshTaskRequest will … | Apple Developer Forums
Background fetch after app is forc… | Apple Developer Forums
…it is widely understood that iOS prevents background execution (such as background fetch, push notifications, or BGTaskScheduler) after a user force-quits an app via the App Switcher.
However, in my app, I have observed that a scheduled BGProcessingTaskRequest still executes even after the app has been explicitly terminated via App Switcher. The task is scheduled using submit(_:error:), and it is clearly running some time after the app has been closed by the user.
That said, the task does run, but it appears to operate under tighter constraints — for example, it may be allowed to run for a shorter duration, and network requests appear to be more restricted compared to when the app is not force-quit.
My questions are:
Are there any documented or undocumented exceptions that allow this kind of behavior after force-quit?
Could this be a bug or a behavior change in recent iOS versions? (I am observing this on iOS 18.3, 18.4, and 18.5)
Any insights, experiences, or clarifications from Apple engineers or fellow developers would be greatly appreciated.
Thank you!
Hi, I'm working on an application on MacOS. It contains a port-forward feature on TCP protocol.
This application has no UI, but a local HTTP server where user can access to configure this application.
I found that my application always exit for unknown purpose after running in backgruond for minutes. I think this is about MacOS's background process controlling.
Source codes and PKG installers are here: https://github.com/burningtnt/Terracotta/actions/runs/16494390417
I've discovered that a system network extension can communicate with a LaunchDaemon (loaded using SMAppService) over XPC, provided that the XPC service name begins with the team ID.
If I move the launchd daemon plist to Contents/Library/LaunchAgents and swap the SMAppService.daemon calls to SMAppService.agent calls, and remove the .privileged option to NSXPCConnection, the system extension receives "Couldn't communicate with a helper application" as an error when trying to reach the LaunchAgent advertised service. Is this limitation by design?
I imagine it is, but wanted to check before I spent any more time on it.
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Service Management
XPC
System Extensions
Network Extension
my app need tracking location all the time both foreground and background. Please suggest how to prevent the app from being terminated. or detect when app is terminated.
Hello 👋
Our team added com.apple.security.temporary-exception.apple-events: com.apple.Terminal recently to our Mac app to be able to tell the terminal to execute a specific command line automatically for the user when clicking a button but we've been rejected during review because of this entitlement so for now we've deleted it and deleted the associated feature.
It concerns the following feature (see attachment).
Context:
Among other things the application enable to review pull request changes (remote) and we would like a button to automatically clone the pull request on disk when user click a button. We would like to use terminal for security reason as when cloning using git command we need ssh keys or other credential and there's no reason (rather than technical ones) that the user provide us such private information that is stored in the ~/.ssh. We prefer think the other way around and tell the user what to execute instead (no credentials involved or shared).
We referred to: https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/AppSandboxTemporaryExceptionEntitlements.html
I admit it's unclear for me if this will imply a 100% rejection or if these entitlements are deprecated.
Is "com.apple.security.temporary-exception.apple-events: com.apple.Terminal" an entitlement that is reserved for special Apple partners ?
Is it an entitlement that we should demonstrate usage first ? Or should we completely remove the feature if we distribute through the App Store ?
Is Apple advice for other APIs to develop such features (execute command line for the user) when distributing through the App Store ?
As said we've disabled the feature for now.
Thank you in advance for those who will take time to answer this,
I am trying to create an app bundle with an xpc service. The main app creates a keychain item, and attempts to share (keychain access groups) with the xpc service it includes in its bundle. However, the xpc service always encounters a 'user interaction not allowed' error regardless of how I create the keychain item. kSecAttrAccessiblei is set to kSecAttrAccessibleWhenUnlockedThisDeviceOnly, the keychain access group is set for both the main app and the xpc service and in the provisioning profile. I've tried signing and notarizing.
Is it ever possible for an xpc service to access the keychain? This all on macos 15.5.
Basically the title. I am trying to implement a local notification to trigger, regardless of internet connection, around 3-5pm if a certain array in the app is not empty to get the user to sync unsaved work with the cloud. I wanted to used the BGAppRefreshTask as I saw it was lightweight and quick for just posting a banner notification but after inspecting it in the console, it looks like it needs internet connection to trigger. Is this the case or am I doing something wrong? Should I be using the BGProcessingTask instead?
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Background Tasks
User Notifications
Service Management framework supports installing and uninstalling services, including Service Management login items, launchd agents, and launchd daemons.
General:
Forums subtopic: App & System Services > Processes & Concurrency
Forums tag: Service Management
Service Management framework documentation
Daemons and Services Programming Guide archived documentation
Technote 2083 Daemons and Agents — It hasn’t been updated in… well… decades, but it’s still remarkably relevant.
EvenBetterAuthorizationSample sample code — This has been obviated by SMAppService.
SMJobBless sample code — This has been obviated by SMAppService.
Sandboxing with NSXPCConnection sample code
WWDC 2022 Session 10096 What’s new in privacy introduces the new SMAppService facility, starting at 07˸07
BSD Privilege Escalation on macOS forums post
Background items showing up with the wrong name forums post
Related forums tags include:
XPC, Apple’s preferred inter-process communication (IPC) mechanism
Inter-process communication, for other IPC mechanisms
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"