Processes & Concurrency

RSS for tag

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

Concurrency Documentation

Post

Replies

Boosts

Views

Activity

Problem with NSSound playback in XPC service
Hello, I run into an issue on Monterey (12.7.5). I have a bundled XPC service in my application which is displaying some stuff and playin sounds via NSSound. I had a problem with playback due to service priority, so I use the trick with a reply block where I send a reply block to the service and basically just retain it and never call it. This worked fine so far, but we have users, predominantly on Monterey, who are having a problem with sound playback. It's choppy and distorted when their machine is under load (where "load" often just means playing a video on YouTube in Chrome). Is there anything else I can do to get the proper priority for my xpc service so I can avoid distorted sound? Additionally the service type is Application and RunLoopType is NSRunLoop with JoinExistingSession set to true. The QoS level of main queue is 0x21 (user interactive) and I'm calling all the NSSound APIs on main queue.
3
0
485
Sep ’24
didFinishLaunchingWithOptions is called in background
Hello, Based on the application runtime logs, after switching to the background (possibly due to the user forcibly closing the application), the app sometimes restarts immediately or after several seconds and executes the didFinishLaunchingWithOptions method (at this point, UIApplicationState == UIApplicationStateBackground). The application itself has not requested background permissions, as shown in the attachment. I am puzzled about what could cause the application to restart in the background several seconds after being forcibly closed. Could you please help clarify the possible reasons for this behavior? (We have considered if it might be due to prewarming, but there is no prewarm flag during the startup.) Thank you.
3
0
365
Sep ’24
Handle background task (BGProcessingTask) in terminated app state
I am having an issue with scheduling daily background task (eg: nightly) when app is in terminated app state (user forcefully terminated the app from app switcher). If the app is in suspended state, I am able to schedule a daily background task. But is there a way to wake up the app nightly and register a BGTask when user forcefully terminates the app.
1
0
370
Sep ’24
What is the principle behind the network filter developed through system expansion starting up with the computer's startup
I developed a network filter using system extensions and placed the system extension program in a container app. I activated the extension and enabled the network filter in the/Applications directory through the container app. After that, my container app process exited, and only the system extension program process in the/Library/SystemExtensions directory was running. After booting up and upgrading the macOS system, the system extension program will be launched, and I learned from the link below that the system extension will be launched with the system at startup: https://developer.apple.com/forums/thread/701986 . But I haven't learned from the official documentation of System Extensions and NetworkExtension why system extensions start with the system and what their principles are. Because the container app under the activation system extension/Application did not start. Has the network filter developed for system expansion been registered in the system related files or frameworks? Ensure that it will start after each startup
2
0
424
Sep ’24
Apps not quitting immediately
Hello all, Recently I observed a strange behaviour on macOS. Some apps with UI, after you quit them (right click on the Dock, select Quit or select Quit from the menubar), the apps are not actually quitting immediately, but in a few seconds (including in Activity Monitor the apps are staying alive). Also, if you open the apps again fast, the same PID is kept. Not all apps do this, some of them, for example WhatsApp. I'm not referring to closing all windows, but explicitly quitting. This was not the case in the past. Is there any reason for this? Is some kind of optimisation I'm not aware of? The actual issue is that in a Swift developed app events like NSWorkspace.didLaunchApplicationNotification or NSWorkspace.didTerminateApplicationNotification are not triggered. Is there any way to tell if an app was closed, even if macOS still keeps it around for a few more seconds? Thank you.
1
0
393
Sep ’24
Helper app is not relaunched after main app is updated from the Mac App Store
I have a macOS app that embeds a helper app in its bundle. That helper app is started by the main app, and from then on it runs independently. I noticed that after updating the main app from the Mac App Store, while the helper app is running, it is not auto-restarted, unlike the main app. What is the correct way to handle this? The main app's bundle looks like this: Main.app - Contents - MacOS - Main - Helper.app
9
0
602
Sep ’24
XCTest to test EndpointSecurity error,ES_NEW_CLIENT_RESULT_ERR_NOT_PRIVILEGED
I tried to use XCTest to test my own project that uses EndpointSecurity, but when I created the esClient I got an error:ES_NEW_CLIENT_RESULT_ERR_NOT_PRIVILEGED, indicating that it was not root. This makes it impossible for me to do coverage tests for the ESClient application. Is there any way I can implement this ESClient test? If so, how should I use it? The project is a macOS program, if I use gcov, but I find I can't get coverage. Using __gcov_flush will indicate that there is no symbol #if !TARGET_IPHONE_SIMULATOR NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; setenv("GCOV_PREFIX", [documentsDirectory cStringUsingEncoding:NSUTF8StringEncoding], 1); setenv("GCOV_PREFIX_STRIP", "13", 1); #endif extern void __gcov_flush(void); __gcov_flush(); #endif
3
0
496
Sep ’24
Issues with @preconcurrency and AVFoundation in Swift 6 on Xcode 16.1/iOS 18 (Worked fine in Swift 5)
Question: I'm working on a project in Xcode 16.1, using Swift 6 with iOS 18. My code is working fine in Swift 5, but I'm running into concurrency issues when upgrading to Swift 6, particularly with the @preconcurrency attribute in AVFoundation. Here is the relevant part of my code: import SwiftUI @preconcurrency import AVFoundation struct OverlayButtonBar: View { ... let audioTracks = await loadTracks(asset: asset, mediaType: .audio) ... // Tracks are extracted before crossing concurrency boundaries private func loadTracks(asset: AVAsset, mediaType: AVMediaType) async -> [AVAssetTrack] { do { return try await asset.load(.tracks).filter { $0.mediaType == mediaType } } catch { print("Error loading tracks: \(error)") return [] } } } Issues: When using @preconcurrency, I get the warning: @preconcurrency attribute on module AVFoundation has no effect. Suggested fix by Xcode is: Remove @preconcurrency. But if I remove @preconcurrency, I get both a warning and an error: Warning: Add '@preconcurrency' to treat 'Sendable'-related errors from module 'AVFoundation' as warnings. Error: Non-sendable type [AVAssetTrack] returned by implicitly asynchronous call to nonisolated function cannot cross actor boundary. (Class AVAssetTrack does not conform to the Sendable protocol (AVFoundation.AVAssetTrack)). This error comes if I attempt to directly access non-Sendable AVAssetTrack in an async context : let audioTracks = await loadTracks(asset: asset, mediaType: .audio) How can I resolve this issue while staying compliant with Swift 6 concurrency rules? Is there a recommended approach to handling non-Sendable types like AVAssetTrack in concurrency contexts? Appreciate any guidance on making this work in Swift 6, especially considering it worked fine in Swift 5. Thanks in advance!
1
0
1.1k
Sep ’24
Handling Main Actor-Isolated Values with `PHPhotoLibrary` in Swift 6
Hello, I’m encountering an issue with the PHPhotoLibrary API in Swift 6 and iOS 18. The code I’m using worked fine in Swift 5, but I’m now seeing the following error: Sending main actor-isolated value of type '() -> Void' with later accesses to nonisolated context risks causing data races Here is the problematic code: Button("Save to Camera Roll") { saveToCameraRoll() } ... private func saveToCameraRoll() { guard let overlayFileURL = mediaManager.getOverlayURL() else { return } Task { do { let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly) guard status == .authorized else { return } try await PHPhotoLibrary.shared().performChanges({ if let creationRequest = PHAssetCreationRequest.creationRequestForAssetFromVideo(atFileURL: overlayFileURL) { creationRequest.creationDate = Date() } }) await MainActor.run { saveSuccessMessage = "Video saved to Camera Roll successfully" } } catch { print("Error saving video to Camera Roll: \(error.localizedDescription)") } } } Problem Description: The error message suggests that a main actor-isolated value of type () -> Void is being accessed in a nonisolated context, potentially leading to data races. This issue arises specifically at the call to PHPhotoLibrary.shared().performChanges. Questions: How can I address the data race issues related to main actor isolation when using PHPhotoLibrary.shared().performChanges? What changes, if any, are required to adapt this code for Swift 6 and iOS 18 while maintaining thread safety and actor isolation? Are there any recommended practices for managing main actor-isolated values in asynchronous operations to avoid data races? I appreciate any points or suggestions to resolve this issue effectively. Thank you!
1
0
1k
Sep ’24
Session, Desktops and login screen
Coming from windows development, I'm trying to understand macOS architecture and how to do certain things. I've already read the Root and Login Sessions AND Service and Daemons AND User Switch Notifications documentation so will frame the questions accordingly. On Windows, there's a concept of User Sessions, each of which contain One or more WindowStations, each of which contain One or more Desktops. Each user gets at least 3 desktops (e.g. Login/Lock/UAC, Screensaver, and default desktop). From what I understand about macOS, it only has Sessions and then a single Desktop. Is that correct? i.e. same display surface is used to display user's desktop, screensaver, sudo prompt and lock screen? What about login screen? Does each user get its own login screen process/window running in their session? or is there a common login screen for all users running in one particular session (root?). How does Fast User switching effect login screen? In a daemon, is it possible to get active console session ID? console meaning the session being displayed on the monitor, whether its login screen, lock screen, user's desktop etc. In a daemon, is it possible to get session switch notifications? E.g. user logged-in and now their desktop is being displayed, user logged-out and now we're back on login screen, or user switched to another user (Fast User switching). How do I get notification of such events in daemon? If no user is logged in which session is pre-login agent running in? and after login does the session ID assigned to pre-login agent stay the same and user's session is assigned a new session ID? Is there always one and only one pre-login agent running? Is it possible to launch pre-login agent and user agents on-demand with custom commandline arguments from a daemon?
7
0
589
Sep ’24
Sandbox app + Parallel Process + LAN Socket (validation app store)
Hello everyone, I need help with an issue that is unclear to me. I developed an application with Unity and now I'm using xCode to distribute it both outside the App Store and on the App Store. As for the first option, no problem, I was able to build the app and upload it for validation. However, regarding the App Store, I have a problem with "App Sandbox," which seems to be mandatory in this case. My application is essentially a party game where one part functions as a desktop application and another part as a mobile application. The desktop application launches a parallel process (which I included in a group within xcode and signed with my developer ID) that makes the two parts communicate through a socket on the local network. When I enable App Sandbox, it seems that the process is not launched by the main application. I have also enabled the two options, Incoming Connection (server/client), under App Sandbox, but it still did not work. I thank you in advance for the support.Sandbox app + parallel process + LAN Socket
5
0
461
Sep ’24
Track system event(shutdown/restart) via launchagent
Hi There, I have to achieve following scenario Track system event on macosx for shutdown and restart and update one plist with same event via launchAgent I have tried following code on launchAgent class MyAgent { init() { let notificationCenter = NSWorkspace.shared.notificationCenter // Register for system shutdown notification notificationCenter.addObserver(self, selector: #selector(handleNotification(_:)), name: NSWorkspace.willPowerOffNotification, object: nil) RunLoop.current.run() } @objc func handleNotification(_ notification: Notification) { var logMessage = "" switch notification.name { case NSWorkspace.willPowerOffNotification: os_log("System is going to shut down at", log: log, type: .default) updatePlistFile(event: "shut down") let fileName = "example.txt" let content = "shut down" createAndWriteFile(fileName: fileName, content: content) logMessage = "System is going to shut down at \(Date())\n" } } } loaded the agent, and tried to restart device, I can't see as it is coming to handleNotification Same code is working fine from sample application but not from launchAgent Is there any restriction is there for NSWorkspace, if is that so, how to track shutdown/restart event from launchAgent or LaunchDaemon Any help will be appreciate
3
0
598
Aug ’24
Daemon needs to get user name
Years ago my daemon was since then using SCDynamicStoreCopyConsoleUser() function and now it longer works. Basically the daemon needs to know the user name of who is using the system. If I restart the daemon,after the login, it gets the user name. I tried run a shell command via my daemon ("id -F") and look likes it still picks the root as user name. So, is there a way to get the current user name using Swift? ProcessInfo.userName fails too
1
0
349
Sep ’24
dispatch_async_f does not return immediatly
Hi, I work on a game for iOS and the framerate decreases progressively when the debugger is attached. Running it for 2mins, it went from 30 to 1 FPS while rendering a simple static scene. I narrowed it down to a call to dispatch_async_f which takes longer to execute over time. clock_t t1 = clock(); dispatch_async_f(queue, context, function); clock_t t2 = clock(); double duration = (double)(t2 -t1)/(double)CLOCKS_PER_SEC; Dodumentation says dispatch_async_f is supposed to return immediatly. So what could explain duration to increases in debug? Am i measuring this incorrectly? The game is written in mixed C++ and ObjC. It uses Metal as graphic API and GCD for dispatching jobs. I have Xcode 13.4.1 and test on an iPhone 13 Pro with iOS 15.7. Thanks.
10
0
2.2k
Oct ’22
Launch another app, collect keypresses, and return to calling app when done
I'm needing the ability in my app (not a public app, but for an in-house private app) to launch a third-party app collect user inputs (like button presses, etc) (don't think this is possible) when done with the third-party app, return to my app with the "results" of the third-party app. My research on this topic is mixed, but am looking for clarification if this is possible. For (1), I know I can launch another app. For (2), I don't think this is possible, but want to confirm For (3), I think the only way this can be done is to (while in the other app) export the data to a shared location, then tab out and select our app to resume. I could tie into the lifecycle to detect when our app resumes then scan the shared location for the results.
1
0
268
Sep ’24
Inexplicable Fence Hang
Hello, My App is getting a Fence hang right after install in a specific scenario. Issue1: I attempted to follow the directions, tried to symbolicate the file etc. however did not have much luck. I was able to pinpoint the lines of code where the hang seems to occur. I did this using simple print and comment out/uncomment blocks of code related to the specific scenario. I was able to do so as, not much is happening on the Main thread in this scenario . Issue 2: The following lines of code ( modified var etc. ) seem to cause the hang. Commenting them out gets rid of the hang across devices, while online/offline etc. I am not sure if I need to use a framework other than AVFoundation. Note: The file extension is mpg The music files are static ( included in the Bundle ) and not accessed from user's playlist etc. import var plyr : AVAudioPlayer? let pth = Bundle.main.path(forResource: "MusicFileName", ofType: "mpg")! let url = URL(fileURLWithPath: pth) do [{](https://www.example.com/) plyr = try AVAudioPlayer(contentsOf: url) plyr?.prepareToPlay() plyr?.play() } catch { // print error etc. } Thanks in advance. I would appreciate some help! Close to submission :)
6
0
531
Sep ’24
Service Management how to register handle_checkbox_toggle?
Hi, I noticed in this page, there is no explanation about who/when/how the method handle_checkbox_toggle is called. Page: https://developer.apple.com/documentation/servicemanagement/updating-helper-executables-from-earlier-versions-of-macos?language=objc Ultimately, how should the app come to know when a app service is allowed or disallowed in System Settings > Login Items ?
1
0
594
Aug ’24