Processes & Concurrency

RSS for tag

Discover how the operating system manages multiple applications and processes simultaneously, ensuring smooth multitasking performance.

Concurrency Documentation

Posts under Processes & Concurrency subtopic

Post

Replies

Boosts

Views

Activity

Processes & Concurrency Resources
General: DevForums subtopic: App & System Services > Processes & Concurrency Processes & concurrency covers a number of different technologies: Background Tasks Resources Concurrency Resources — This includes Swift concurrency. Service Management Resources XPC Resources Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
77
Jul ’25
Electron app with Express + Python child processes not running in macOS production build
Hi all, I’ve built an Electron application that uses two child processes: An Express.js server A Python executable (packaged .exe/binary) During the development phase, everything works fine — the Electron app launches, both child processes start, and the app functions as expected. But when I create a production build for macOS, the child processes don’t run. Here’s a simplified snippet from my electron.mjs: import { app, BrowserWindow } from "electron"; import { spawn } from "child_process"; import path from "path"; let mainWindow; const createWindow = () => { mainWindow = new BrowserWindow({ width: 1200, height: 800, webPreferences: { nodeIntegration: true, }, }); mainWindow.loadFile("index.html"); // Start Express server const serverPath = path.join(process.resourcesPath, "app.asar.unpacked", "server", "index.js"); const serverProcess = spawn(process.execPath, [serverPath], { stdio: "inherit", }); // Start Python process const pythonPath = path.join(process.resourcesPath, "app.asar.unpacked", "python", "myapp"); const pythonProcess = spawn(pythonPath, [], { stdio: "inherit", }); serverProcess.on("error", (err) => console.error("Server process error:", err)); pythonProcess.on("error", (err) => console.error("Python process error:", err)); }; app.whenReady().then(createWindow); I’ve already done the following: Configured package.json with the right build settings Set up extraResources / asarUnpack to include the server and Python files Verified both child processes work standalone Questions: What’s the correct way to package and spawn these child processes for macOS production builds? Do I need to move them into a specific location (like Contents/Resources/app.asar.unpacked) and reference them differently? Is there a more reliable pattern for handling Express + Python child processes inside an Electron app bundle? Any insights or working examples would be really appreciated!
1
0
16
20h
Mac: Best way to distinguish native app process and script process spawned from executable (e.g. python node) through process_id
I'm working on a Mac app that receives a process ID via NSXPCConnection, and I'm trying to figure out the best way to determine whether that process is a native macOS app like Safari—with bundles and all—or just a script launched by something like Node or Python. The executable is signed with a Team ID using codesign. I was thinking about getting the executable's path as one way to handle it, but I’m wondering if there’s a more reliable method than relying on the folder structure.
1
0
137
20h
How is BGContinuedProcessingTask intended to be used?
Hello, I'm trying to adopt the new BGContinuedProcessingTask API, but I'm having a little trouble imagining how the API authors intended it be used. I saw the WWDC talk, but it lacked higher-level details about how to integrate this API, and I can't find a sample project. I notice that we can list wildcard background task identifiers in our Info.plist files now, and it appears this is to be used with continued tasks - a user might start one video encoding, then while it is ongoing, enqueue another one from the same app, and these tasks would have identifiers such as "MyApp.VideoEncoding.ABCD" and "MyApp.VideoEncoding.EFGH" to distinguish them. When it comes to implementing this, is the expectation that we: a) Register a single handler for the wildcard pattern, which then figures out how to fulfil each request from the identifier of the passed-in task instance? Or b) Register a unique handler for each instance of the wildcard pattern? Since you can't unregister handlers, any resources captured by the handler would be leaked, so you'd need to make sure you only register immediately before submission - in other words register + submit should always be called as a pair. Of course, I'd like to design my application to use this API as the authors intended it be used, but I'm just not entirely sure what that is. When I try to register a single handler for a wildcard pattern, the system rejects it at runtime (while allowing registrations for each instance of the pattern, indicating that at least my Info.plist is configured correctly). That points towards option B. If it is option B, it's potentially worth calling that out in documentation - or even better, perhaps introduce a new call just for BGContinuedProcessingTask instead of the separate register + submit calls? Thanks for your insight. K Aside: Also, it would be really nice if the handler closure would be async. Currently if you need to await on something, you need to launch an unstructured Task, but that causes issues since BGContinuedProcessingTask is not Sendable, so you can't pass it in to that Task to do things like update the title or mark the BGTask as complete.
7
0
146
1d
BGTaskScheduler fails to match unique identifiers to a registered wildcard handler for BGContinuedProcessingTask
Testing Environment: iOS Version: 26.0 Beta 7 Xcode Version: 17.0 Beta 6 Device: iPhone 16 Pro Description: We are implementing the new BGContinuedProcessingTask API and are using the wildcard identifier notation as described in the official documentation. Our Info.plist is correctly configured with a permitted identifier pattern, such as com.our-bundle.export.*. We then register a single launch handler for this exact wildcard pattern. We are performing this registration within a UIViewController, which is a supported pattern as BGContinuedProcessingTask is explicitly exempt from the "register before applicationDidFinishLaunching" requirement, according to the BGTaskScheduler.h header file. The register method correctly returns true, indicating the registration was successful. However, when we then try to submit a task with a unique identifier that matches this pattern (e.g., com.our-bundle.export.UUID), the BGTaskScheduler.shared.submit() call throws an NSInternalInconsistencyException and terminates the app. The error reason is: 'No launch handler registered for task with identifier com.our-bundle.export.UUID'. This indicates that the system is not correctly matching the specific, unique identifier from the submit call to the registered wildcard pattern handler. This behavior contradicts the official documentation. Steps to Reproduce: Create a new Xcode project. In Signing & Capabilities, add "Background Modes" (with "Background processing" checked) and "Background GPU Access". Add a permitted identifier (e.g., "com.company.test.*") to BGTaskSchedulerPermittedIdentifiers in Info.plist. In a UIViewController's viewDidLoad, register a handler for the wildcard pattern. Check that the register method returns true. Immediately after, try to submit a BGContinuedProcessingTaskRequest with a unique identifier that matches the pattern. Expected Results: The submit call should succeed without crashing, and the task should be scheduled. Actual Results: The app crashes immediately upon calling submit(). The console shows an uncaught NSInternalInconsistencyException with the reason: 'No launch handler registered for task with identifier com.company.test.UUID'. Workaround: The issue can be bypassed if we register a new handler for each unique identifier immediately before submitting a request with that same unique identifier. This strongly suggests the bug is in the system's wildcard pattern-matching logic.
1
0
36
1d
Using raise in GCD can cause timing issues with the signal mechanism.
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
4
0
143
1d
Background Tasks Resources
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.
0
0
3.8k
3d
XPC Resources
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"
0
0
2.8k
1w
BGContinuedProcessingTask code pauses when device is locked
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?
4
0
127
1w
macOS 14 XPC vs Foundation XPC
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??
2
0
622
1w
[iOS 26 Beta] BGTaskScheduler.supportedResources incorrectly reports no GPU support for BGContinuedProcessingTask on capable hardware
Testing Environment: iOS: 26.0 Beta 7 Xcode: Beta 6 Description: We are implementing the new BGContinuedProcessingTask API introduced in iOS 26. We have followed the official documentation and WWDC session guidance to configure our project. The Background Modes (processing) and Background GPU Access capabilities have been added in Xcode. The com.apple.developer.background-tasks.continued-processing.gpu entitlement is present and set to in the .entitlements file. The provisioning profile details viewed within Xcode explicitly show that the "Background GPU Access" capability and the corresponding entitlement are included. Despite this correct configuration, when running the app on supported hardware (iPhone 16 Pro), a call to BGTaskScheduler.supportedResources.contains(.gpu) consistently returns false. This prevents us from setting request.requiredResources = .gpu. As a result, when the BGContinuedProcessingTask starts without the GPU resource flag, our internal Metal-based exporter attempts to access the GPU and is terminated by the system, throwing an IOGPUMetalError: Insufficient Permission (to submit GPU work from background). We have performed extensive debugging, including a full reset of the provisioning profile (removing/re-adding capabilities, toggling automatic signing, cleaning build folders, and reinstalling the app), but the issue persists. This strongly suggests a bug in the iOS 26 beta where the runtime is failing to correctly validate a valid entitlement. Additionally, we've observed inconsistent behavior across devices. On an A16-based iPad, the task submits successfully (BGTaskScheduler.submit does not throw an error), but the launch handler is never invoked by the system. On the iPhone 16 Pro, the handler is invoked, but we encounter the supportedResources issue described above. This leads us to ask for clarification on the exact hardware requirements for this feature. We hypothesize that it may be limited to devices that support Apple Intelligence (A17 Pro and newer). Could you please confirm this and provide official documentation on the device support criteria? Steps to Reproduce: Create a new Xcode project. In Signing & Capabilities, add "Background Modes" (with "Background processing" checked) and "Background GPU Access". Add a permitted identifier (e.g., "com.company.test.*") to BGTaskSchedulerPermittedIdentifiers in Info.plist. In application(_:didFinishLaunchingWithOptions:) or a ViewController's viewDidLoad, log the result of BGTaskScheduler.shared.supportedResources.contains(.gpu). Build and run on a physical, supported device (e.g., iPhone 16 Pro). Expected Results: The log should indicate that BGTaskScheduler.shared.supportedResources.contains(.gpu) returns true. Actual Results: The log shows that BGTaskScheduler.shared.supportedResources.contains(.gpu) returns false.
3
0
100
2w
How can I get a Subscriber to subscribe to get only 4 elements from an array?
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?
0
0
87
2w
App is getting terminated by OS even after calling BG task expiration
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
1
0
78
3w
BGContinuedProcessingTask compatibility with background URLSession
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!
2
0
61
3w
How to correctly deploy bundled launchdaemons/launchagents?
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.
7
0
733
Aug ’25
Expected behavior from apps when MacOS goes to sleep
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?
1
0
70
Aug ’25
dispatch_main and main thread local variables
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 gross 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
1
0
86
Jul ’25
Background App Refresh
Hi, I have a couple questions about background app refresh. First, is the function RefreshAppContentsOperation() where to implement code that needs to be run in the background? Second, despite importing BackgroundTasks, I am getting the error "cannot find operationQueue in scope". What can I do to resolve that? Thank you. func scheduleAppRefresh() { let request = BGAppRefreshTaskRequest(identifier: "peaceofmindmentalhealth.RoutineRefresh") // Fetch no earlier than 15 minutes from now. request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) do { try BGTaskScheduler.shared.submit(request) } catch { print("Could not schedule app refresh: \(error)") } } func handleAppRefresh(task: BGAppRefreshTask) { // Schedule a new refresh task. scheduleAppRefresh() // Create an operation that performs the main part of the background task. let operation = RefreshAppContentsOperation() // Provide the background task with an expiration handler that cancels the operation. task.expirationHandler = { operation.cancel() } // Inform the system that the background task is complete // when the operation completes. operation.completionBlock = { task.setTaskCompleted(success: !operation.isCancelled) } // Start the operation. operationQueue.addOperation(operation) } func RefreshAppContentsOperation() -> Operation { }
21
0
291
Jul ’25
Reliable 30-minute background data fetching for safety-critical monitoring app?
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.
1
0
500
Jul ’25
BGProcessingTaskRequest executing even after force-quit from App Switcher
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!
5
0
117
Jul ’25