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

i can not run "pgrep" or "ps" in sandbox?
Hi. I'm trying to learn macOS app development. i'm trying to run unix commands: func execute(_ command: String) throws -> String { let process = Process() let pipe = Pipe() process.executableURL = URL(fileURLWithPath: "/bin/bash") process.arguments = ["-c", command] process.standardOutput = pipe // process.standardError try process.run() process.waitUntilExit() guard let data = try pipe.fileHandleForReading.readToEnd() else { throw CommandError.readError } guard let output = String(data: data, encoding: .utf8) else { throw CommandError.invalidData } process.waitUntilExit() guard process.terminationStatus == 0 else { throw CommandError.commandFailed(output) } return output } when try to run "pgrep" in sandbox mode ON, i get: sysmon request failed with error: sysmond service not found error. if i turn it off it works. i don't know what to do. anyone can help me out?
2
0
232
Mar ’25
NotificationCenter.notifications(named:) appears to buffer internally and can drop notifications, but is this documented anywhere?
I've experimentally seen that the notifications(named:) API of NotificationCenter appears to buffer observed notifications internally. In local testing it appears to be limited to 8 messages. I've been unable to find any documentation of this fact, and the behavior seems like it could lead to software bugs if code is not expecting notifications to potentially be dropped. Is this behavior expected and documented somewhere? Here is a sample program demonstrating the behavioral difference between the Combine and AsyncSequence-based notification observations: @Test nonisolated func testNotificationRace() async throws { let testName = Notification.Name("TestNotification") let notificationCount = 100 var observedAsyncIDs = [Int]() var observedCombineIDs = [Int]() let subscribe = Task { @MainActor in print("setting up observer...") let token = NotificationCenter.default.publisher(for: testName) .sink { value in let id = value.userInfo?["id"] as! Int observedCombineIDs.append(id) print("🚜 observed note with id: \(id)") } defer { extendLifetime(token) } for await note in NotificationCenter.default.notifications(named: testName) { let id: Int = note.userInfo?["id"] as! Int print("🚰 observed note with id: \(id)") observedAsyncIDs.append(id) if id == notificationCount { break } } } let post = Task { @MainActor in for i in 1...notificationCount { NotificationCenter.default.post( name: testName, object: nil, userInfo: ["id": i] ) } } _ = await (post.value, subscribe.value) #expect(observedAsyncIDs.count == notificationCount) // 🛑 Expectation failed: (observedAsyncIDs.count → 8) == (notificationCount → 100) #expect(observedCombineIDs == Array(1...notificationCount)) print("done") }
2
0
174
2w
SMAppService Error 108 'Unable to read plist' on macOS 15 - Comprehensive Analysis & Test Case
SMAppService Error 108 "Unable to read plist" on macOS 15 Sequoia - Comprehensive Test Case Summary We have a fully notarized SMAppService implementation that consistently fails with Error 108 "Unable to read plist" on macOS 15 Sequoia, despite meeting all documented requirements. After systematic testing including AI-assisted analysis, we've eliminated all common causes and created a comprehensive test case. Error: SMAppServiceErrorDomain Code=108 "Unable to read plist: com.keypath.helperpoc.helper" 📋 Complete Repository: https://github.com/malpern/privileged_helper_help What We've Systematically Verified ✅ Perfect bundle structure: Helper at Contents/MacOS/, plist at Contents/Library/LaunchDaemons/ Correct SMAuthorizedClients: Embedded in helper binary via CREATE_INFOPLIST_SECTION_IN_BINARY=YES Aligned identifiers: Main app, helper, and plist all use consistent naming Production signing: Developer ID certificates with full Apple notarization and stapling BundleProgram paths: Tested both Contents/MacOS/helperpoc-helper and simplified helperpoc-helper Entitlements: Tested with and without com.apple.developer.service-management.managed-by-main-app What Makes This Different Systematic methodology: Not a "help me debug" post - we've done comprehensive testing Expert validation: AI analysis helped eliminate logical hypotheses Reproduction case: Minimal project that demonstrates the issue consistently Complete documentation: All testing steps, configurations, and results documented Use Case Context We're building a keyboard remapper that integrates with https://github.com/jtroo/kanata and needs privileged daemon registration for system-wide keyboard event interception. Key Questions Does anyone have a working SMAppService implementation on macOS 15 Sequoia? Are there undocumented macOS 15 requirements we're missing? Is Error 108 a known issue with specific workarounds? Our hypothesis: This appears to be a macOS 15 system-level issue rather than configuration error, since our implementation meets all documented Apple requirements but fails consistently. Has anyone encountered similar SMAppService issues on macOS 15, or can confirm a working implementation?
2
0
298
Jul ’25
Bluetooth work with BGTaskScheduler
Hi All, I'm working on an app that needs to connect to BLE device and on defined schedules download data from the device. the amount of data is segnificant and might take around a minute to download. we tought about utilizing both state restoration and preservation for app waking and scheduling (triggered by the ble peripheral) and BGTaskScheduler to schedule a task that will handle a long running task to manage the full data download. now, will this solution in general valid? isnt it a "hack" that goes around the 10s limit that state restoration enforces? i know there are limitations for BGTask (like when it runs, it might be terminated by the system etc) but considering that, can we proceed with this approach without breaching apple guidelines? thank you in advance!
2
0
152
Oct ’25
Flutter library that basically makes a call every "x" minutes if the app is in the background.
Hi everyone, could you help us? We implemented a Flutter library that basically makes a call every x minutes if the app is in the background, but when I generate the version via TestFlight for testing, it doesn't work. Can you help us understand why? Below is a more detailed technical description. Apple Developer Technical Support Request Subject: BGTaskScheduler / Background Tasks Not Executing in TestFlight - Flutter App with workmanager Plugin Issue Summary Background tasks scheduled using BGTaskScheduler are not executing when the app is distributed via TestFlight. The same implementation works correctly when running the app locally via USB/Xcode debugging. We are developing a Flutter application that needs to perform periodic API calls when the app is in the background. We have followed all documentation and implemented the required configurations, but background tasks are not being executed in the TestFlight build. App Information Field Value App Version 3.1.15 (Build 311) iOS Minimum Deployment Target iOS 15.0 Framework Flutter Flutter SDK Version ^3.7.2 Technical Environment Flutter Dependencies (Background Task Related) Package Version Purpose workmanager ^0.9.0+3 Main background task scheduler (uses BGTaskScheduler on iOS 13+) flutter_background_service ^5.0.5 Background service management flutter_background_service_android ^6.2.4 Android-specific background service flutter_local_notifications ^19.4.2 Local notifications for background alerts timezone ^0.10.0 Timezone support for scheduling Other Relevant Flutter Dependencies Package Version firebase_core 4.0.0 firebase_messaging (via native Podfile) sfmc (Salesforce Marketing Cloud) ^9.0.0 geolocator ^14.0.0 permission_handler ^12.0.0+1 Info.plist Configuration We have added the following configurations to Info.plist: UIBackgroundModes <key>UIBackgroundModes</key> <array> <string>location</string> <string>remote-notification</string> <string>processing</string> </array> ### BGTaskSchedulerPermittedIdentifiers ```xml <key>BGTaskSchedulerPermittedIdentifiers</key> <array> <string>br.com.unidas.apprac.ios.workmanager.carrinho_api_task</string> <string>br.com.unidas.apprac.ios.workmanager</string> <string>be.tramckrijter.workmanager.BackgroundTask</string> </array> **Note:** We included multiple identifier formats as recommended by the `workmanager` Flutter plugin documentation: 1. `{bundleId}.ios.workmanager.{taskName}` - Custom task identifier 2. `{bundleId}.ios.workmanager` - Default workmanager identifier 3. `be.tramckrijter.workmanager.BackgroundTask` - Plugin's default identifier (as per plugin documentation) ## AppDelegate.swift Configuration We have configured the `AppDelegate.swift` with the following background processing setup: ```swift // In application(_:didFinishLaunchingWithOptions:) // Configuration to enable background processing via WorkManager // The "processing" mode in UIBackgroundModes allows WorkManager to use BGTaskScheduler (iOS 13+) // This is required to execute scheduled tasks in background (e.g., API calls) // Note: User still needs to have Background App Refresh enabled in iOS settings if UIApplication.shared.backgroundRefreshStatus == .available { // Allows iOS system to schedule background tasks with minimum interval UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum) } ## WorkManager Implementation (Dart/Flutter) ### Initialization ```dart /// Initializes WorkManager static Future<void> initialize() async { await Workmanager().initialize(callbackDispatcher, isInDebugMode: false); print('WorkManagerService: WorkManager initialized'); } ### Task Registration /// Schedules API execution after a specific delay ## Observed Behavior ### Works (Debug/USB Connection) - When running the app via Xcode/USB debugging - Background tasks are scheduled and executed as expected - API calls are made successfully when the app is backgrounded ### Does NOT Work (TestFlight) - When the app is distributed via TestFlight - Background tasks appear to be scheduled (no errors in code) - Tasks are **never executed** when the app is in background - We have tested with: - Background App Refresh enabled in iOS Settings - App used frequently - Device connected to WiFi and charging - Waited for extended periods (hours) ## Possible heart points 1. **Are there any additional configurations required for `BGTaskScheduler` to work in TestFlight/Production builds that are not required for debug builds?** 2. **Is the identifier format correct?** We are using: `br.com.unidas.apprac.ios.workmanager.carrinho_api_task` - Should it match exactly with the task name registered in code? 3. **Are there any known issues with Flutter's `workmanager` plugin and iOS BGTaskScheduler in production environments?** 4. **Is there any way to verify through logs or system diagnostics if the background tasks are being rejected by the system?** 5. **Could there be any conflict between our other background modes (`location`, `remote-notification`) and `processing`?** 6. **Does the Salesforce Marketing Cloud SDK (SFMC) interfere with BGTaskScheduler operations?** ## Additional Context - We have verified that `Background App Refresh` is enabled for our app in iOS Settings - The app has proper entitlements for push notifications and location services - Firebase, SFMC (Salesforce Marketing Cloud), and other SDKs are properly configured - The issue is **only** present in TestFlight builds, not in debug/USB-connected builds ## References - [Apple Documentation - BGTaskScheduler](https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler) - [Apple Documentation - Choosing Background Strategies](https://developer.apple.com/documentation/backgroundtasks/choosing_background_strategies_for_your_app) Thank you
2
0
54
2w
Using protocols with XPC C API instead of dictionaries for sending and receiving messages
I have followed this post for creating a Launch Agent that provides an XPC service on macOS using Swift- post link - https://rderik.com/blog/creating-a-launch-agent-that-provides-an-xpc-service-on-macos/ In the swift code the interface of the XPC service is defined by protocols which makes the code nice and neat. I want to implement the XPC service using C APIs for XPC, and C APIs send and receive messages using dictionaries, which need manual handling with conditional statements. I want to know if its possible to go with the protocol based approach with C APIs.
2
0
508
Jan ’25
System Network Extension XPC with LaunchAgent
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.
1
0
214
Jul ’25
Effect of app nap of Timer
I'm developing a macOS application that tracks the duration of a user's session using a timer, which is displayed both in the main window and in an menu bar extra view. I have a couple of questions regarding the timer's behavior: What happens to the timer if the user closes the application's window (causing the app to become inactive) but does not fully quit it? Does the timer continue to run, pause, or behave in some other way? Will the app nap feature stop the timer when app is in-active state? When the application is inactive and the system is either in sleep mode or locked, does the timer’s tolerance get affected? In other words, will the timer fire with any additional delay compared to its scheduled time under these conditions?
1
0
76
Mar ’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
544
Jul ’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
122
Jul ’25
Issue with Developer App Crashing on iPad Upon Launch
Recently, after updating the Developer app to the latest version, my iPad has been unable to open this app as it crashes immediately upon launch. Prior to the update, the app functioned normally. My device is an 11-inch iPad Pro from 2021, running iPadOS 17.3. I have tried troubleshooting steps such as reinstalling the app and restarting the device, but these actions have not resolved the issue. However, I need to use this specific version of the system, iPadOS 17.3, for software testing purposes and cannot upgrade the system. Other apps on my device work normally without any issues. Is there a solution to this problem? I have attempted to contact the developer support team in China, but they were also unable to provide a resolution. This issue is reproducible 100% of the time on my iPad.
1
0
361
Jan ’25
Effect of App Nap on Timer
I'm developing a macOS application that tracks the duration of a user's session using a timer, which is displayed both in the main window and in an menu bar extra view. I have a couple of questions regarding the timer's behavior: What happens to the timer if the user closes the application's window (causing the app to become inactive) but does not fully quit it? Does the timer continue to run, pause, or behave in some other way? Will the app nap feature stop the timer when app is in-active state?
1
0
118
Mar ’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
113
Aug ’25
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
107
Aug ’25
Is background processing even possible?
Hello, aspiring programmer here. I am developing a StepCounter APP, which keeps track of how many steps I have taken and sends to an MQTT server. I am trying to make this happen even while the app is not in focus, but so far I have not been able to get this working. First tried with silent background music, which seemed pretty inconsistent and inpractical, since I usually play youtube videoes while walking, making the app stop with its silent audio. Then tried GPS, which didnt really do anything (could be implementation problem). Has anyone made background processing work for their apps?
1
0
111
Mar ’25
HELP: Privileged Helper With SMAppService
Hi! I've been developing iOS and macOS apps for many years, but now I am looking to dive into smth i have never touched before, namely privileged helpers, and i am struggling hard trying to find my footing. Here’s my use case: I have a CLI tool that requires elevated privileges. I want to create a menu bar app that can interact with this tool, but I’m struggling to find solid documentation or examples of how to accomplish this using SMAppService. I might just be missing something obvious. If anyone could point me toward relevant documentation, examples, articles, tutorials, or even a WWDC session that covers running privileged helpers with SMAppService, I would greatly appreciate it. Thanks in advance!
1
0
479
Feb ’25
How to correctly access and handle background operations on IOS
Hello, aspiring programmer here. I am developing a StepCounter APP, which keeps track of how many steps I have taken and sends to an MQTT server. I am trying to make this happen even while the app is not in focus, but so far I have not been able to get this working. First tried with silent background music, which seemed pretty inconsistent and inpractical, since I usually play youtube videoes while walking, making the app stop with its silent audio. Then tried GPS, which didnt really do anything (could be implementation problem). Has anyone made background processing work for their apps?
1
0
140
Mar ’25
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
128
Sep ’25
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
203
Sep ’25