I am developing a macOS non-interactive macOS application which does not show any ui.
i want to block main thread and do all the work on worker thread . Once done with work in worker thread, want to unblock main thread by exiting event loop to terminate application.
Because i dont want to show any UI or use any Foundation/Cocoa functionality, i am thinking of using CFRunLoop to block main thread from exiting until i finish my work in worker thread.
When i tried this in a project, I am able to finish work in worker thread after block main thread using CFRunLoop.
I also want this application to be a bundled application, which can be launched by double clicking on application bundle . But when i tried it in my xcode project by launching it using double clicking on application bundle, application keeps on toggling/bouncing in the dock menu with a status "Not responding". Although i am able to complete my work in worker thread.
import Foundation
let runLoop = CFRunLoopGetCurrent()
func workerTask() {
DispatchQueue.global().async {
print("do its work")
sleep(5) // do some work
print("calling exit event loop")
CFRunLoopStop(runLoop)
print ("unblocking main thread")
}
}
workerTask ()
// blocking main thread
print ("blocked main thread")
CFRunLoopRun()
print ("exit")
Why i am getting this application bouncing in doc menu behavior ? I tried by using NSApplicationMain instead of CFRunLoop in my project, in that case i didnt get this behavior .
Does NSApplicationMain does some extra work before starting NSRunLoop which i am not doing while using CFRunLoop, which is showing this toggling/Bouncing application icon in Dock menu ?
or Is this bouncing app icon issue is related to run loop i am using which is CFRunLoop ?
Note : If i dont use a bundled application and use a commandline application then i am able to do all steps in worker thread and exit main thread as i wanted after finishing my work . But i need to do all this in application which can be launched using double clicking (bundled applcation).
If not by using CFRunLoop, then how can i achive this ? - Create a application which shows no UI and do all work in worker thread while main thread is blocked. Once work is done unblock main thread and exit. And user should be able to launch application using double click the application icon.
How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here
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
When using the old withTaskCancellationHandler(operation:onCancel:isolation:) to run background tasks, you were notified that the background task gets cancelled via the handler being called. SwiftUI provides the backgroundTask(_:action:) modifier which looks quite handy. However how can I check if the background task will be cancelled to avoid being terminated by the system?
I have tried to check that via Task.isCancelled but this always returns false no matter what.
Is this not possible when using the modifier in which case I should file a bug report?
Thanks for your help
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
SwiftUI
Background Tasks
WidgetKit
Hello Apple Developer Community,
I am developing a medical app that is classified as Class B according to FDA regulations. The app connects to a medical device using Bluetooth Low Energy (BLE) to collect critical medical data such as ECG readings. To ensure accurate data collection and maintain the quality of the medical readings, the app needs to wake up every five minutes in the background and perform tasks for approximately 30 seconds.
I understand that iOS has strict limitations on background execution to preserve battery and system performance. However, due to the medical nature of the app and the need for periodic data collection, I am seeking guidance on the following:
If I can provide documentation that the app is associated with an FDA-approved Class B medical device, would Apple allow more lenient background task execution policies?
Are there specific APIs, such as BackgroundTasks, CoreBluetooth, or other recommended strategies, that could help me achieve this behavior reliably?
Is there a process to apply for an exception or special consideration for medical apps that require periodic background activity?
Any insights or recommendations would be greatly appreciated. Thank you!
I have implemented a XPC server using C APIs. I want to write unit tests for it.
I came across the following links that use Swift APIs-
Testing and Debugging XPC Code With an Anonymous Listener
TN3113
I have tried to write anonymous listener code and the client code in the same file, using C APIs-
#include <unistd.h>
#include <syslog.h>
#include <pthread.h>
#include <stdio.h>
#include <xpc/xpc.h>
#include <xpc/connection.h>
#include <CoreFoundation/CoreFoundation.h>
static void Anon_Client_Connection_Handler(xpc_connection_t connection, xpc_object_t clientMessage)
{
const char *description = xpc_copy_description(clientMessage);
printf("Event received - %s\n", description);
free((void *)description);
xpc_type_t type = xpc_get_type(clientMessage);
if (type == XPC_TYPE_ERROR)
{
if (clientMessage == XPC_ERROR_CONNECTION_INVALID)
printf("Client_Connection_Handler received invalid connection n");
else if (clientMessage == XPC_ERROR_TERMINATION_IMMINENT)
printf("Client_Connection_Handler received termination notice n");
}
else
{
const char *clientMsg = xpc_dictionary_get_string(clientMessage, "message");
printf("Received from client: %s ", clientMsg);
}
}
static void Anon_Listener_Connection_Handler(xpc_connection_t connection)
{
printf("Anon_Listener_Connection_Handler called, setting up event handler \n");
xpc_connection_set_event_handler(connection, ^(xpc_object_t clientMessage) {
printf("Processing the connection! \n");
Anon_Client_Connection_Handler(connection, clientMessage);
});
xpc_connection_resume(connection);
}
int main(int argc, const char *argv[])
{
xpc_connection_t anon_listener = xpc_connection_create(NULL, NULL);
xpc_connection_set_event_handler(anon_listener, ^(xpc_object_t clientConnection) {
printf("Client tried to connect \n");
Anon_Listener_Connection_Handler(clientConnection);
});
xpc_connection_resume(anon_listener);
printf("\nINFO Anonymous connection resumed");
xpc_object_t anon_endpoint = xpc_endpoint_create(anon_listener);
xpc_connection_t clientConnection = xpc_connection_create_from_endpoint(anon_endpoint);
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_string(message, "message", "client's message");
xpc_connection_send_message_with_reply(clientConnection, message, dispatch_get_main_queue(), ^(xpc_object_t event) {
printf("\nINFO inside reply");
const char *description = xpc_copy_description(event);
printf("\nINFO %s",description);
free((void *)description);
});
xpc_release(message);
xpc_release(anon_listener);
printf("\nINFO Releasing listener");
xpc_release(anon_endpoint);
printf("\nINFO Releasing endpoint");
// dispatch_main();
return 0;
}
and this is the output I get
INFO Anonymous connection resumed
INFO Releasing listener
INFO Releasing endpoint
I am not able to connect to the client and exchange messages. Where am I going wrong?
I've been experimenting with the new low-level Swift API for XPC (XPCSession and XPCListener). The ability to send and receive Codable messages is an appealing alternative to making an @objc protocol in order to use NSXPCConnection from Swift — I can easily create an enum type whose cases map onto the protocol's methods.
But our current XPC code validates the incoming connection using techniques similar to those described in Quinn's "Apple Recommended" response to the "Validating Signature Of XPC Process" thread. I haven't been able to determine how to do this with XPCListener; neither the documentation nor the Swift interface have yielded any insight.
The Creating XPC Services article suggests using Xcode's XPC Service template, which contains this code:
let listener = try XPCListener(service: serviceName) { request in
request.accept { message in
performCalculation(with: message)
}
}
The apparent intent is to inspect the incoming request and decide whether to accept it or reject it, but there aren't any properties on IncomingSessionRequest that would allow the service to make that decision. Ideally, there would be a way to evaluate a code signing requirement, or at least obtain the audit token of the requesting process.
(I did notice that a function xpc_listener_set_peer_code_signing_requirement was added in macOS 14.4, but it takes an xpc_listener_t argument and I can't tell whether XPCListener is bridged to that type.)
Am I missing something obvious, or is there a gap in the functionality of XPCListener and IncomingSessionRequest?
Are there any plans to add RBI support (the sending keyword) to the OSAllocatedLock interface? So it could be used with non-sendable objects without surrendering to the unchecked API
Is the title possible ? I tried [[thread valueForKey:@"_private"] valueForKey:@"tid"] but the tid was not kvc compliant. private apis are alright because this is just for testing remote process thread creation. I already have a working method but it has hardcoded assembly so you can't do anything else.
this question is mainly for Quinn (figured he may know something about this)
I am using C APIs for XPC communication.
When my XPC server gets a xpc_dictionary as a message, I use xpc_dictionary_get_string to get the string which is of type const char*. Afterwards, when I try to free up the memory for the string, I get an error.
I could not find any details on why this happens.
Does XPC handle the lifecycle of these C strings ?
I did some tests to see the behaviour.
The following code snippet prints a string temp before and after releasing the dictionary memory.
char* string = "dummy-string";
xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0); xpc_dictionary_set_string(dict, "str", string);
const char* temp = xpc_dictionary_get_string(reply, "str");
printf("temp before release: %s\n", temp);
xpc_release(reply);
printf("temp after release: %s\n", temp);
output:
# temp before release: dummy-string
# temp after release:
I tried to free the variable temp before and after releasing dict .
char* string = "dummy-string";
xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0); xpc_dictionary_set_string(dict, "str", string);
const char* temp = xpc_dictionary_get_string(dict, "str");
printf("temp before release: %s\n", temp);
free((void *)temp); // case 1
xpc_release(dict);
// free((void *)temp); // case 2
printf("temp after release: %s\n", temp);
in both the cases i got the output:
# temp before release: dummy-string
# app(18502,0x1f02fc840) malloc: Double free of object 0x145004a20
# app(18502,0x1f02fc840) malloc: *** set a breakpoint in malloc_error_break to debug
# SIGABRT: abort
# PC=0x186953720 m=0 sigcode=0
# signal arrived during cgo execution
# ...
# ...
So i am pretty new to Xcode, but i have been using Python and other language for some while. But I am quite new to the game of view and view control. So it may be that i have over complicated this a bit - and it may be that I have some wrong understanding of the dependencies and appcontroller (that i thought would be a good idea). So here we have a main file we call it app.swift, we have a startupmanager.swift, a appcoordinator and a dependeciescontainer. But it may be that this is either a overkill - or that I am doing it wrong.
So my thought was that i had a dependeciecontainer, a appcoordinator for the views and a startupmanager that controll the initialized fetching. I have controlled the memory when i run it - checking if it is higher, lower eg - but it was first when i did my 2 days profile i saw a lot of new errors, like this: Fikser(7291,0x204e516c0) malloc: xzm: failed to initialize deferred reclamation buffer (46). and i also get macro errors, probably from the @Query in my feedview.
So my thought was that a depencecie manager and a startupmanager was a good idea together with a app coordinator.
But maybe I am wrong - maybe this is not a good idea? Or maybe I am doing some things twice? I have added a lot of prints and debugs for checking. But it seems that it starts off to heavy?
import SwiftUI
import Combine
@MainActor
class AppCoordinator: ObservableObject {
@Published var isLoggedIn: Bool = false
private var authManager: AuthenticationManager = .shared
private var cancellables = Set<AnyCancellable>()
private let startupManager: StartupManager
private let container: DependencyContainer
@Published var path = NavigationPath()
enum Screen: Hashable, Identifiable {
case profile
case activeJobs
case offers
case message
var id: Self { self }
}
init(container: DependencyContainer) {
self.container = container
self.startupManager = container.makeStartupManager()
setupObserving()
startupManager.start()
print("AppCoordinator initialized!")
}
private func setupObserving() {
authManager.$isAuthenticated
.receive(on: RunLoop.main)
.sink { [weak self] isAuthenticated in
self?.isLoggedIn = isAuthenticated
}
.store(in: &cancellables)
}
func userDidLogout() {
authManager.logout()
path.removeLast(path.count)
}
func showProfile() {
path.append(Screen.profile)
}
func showActiveJobs() {
path.append(Screen.activeJobs)
}
func showOffers() {
path.append(Screen.offers)
}
func showMessage() {
path.append(Screen.message)
}
@ViewBuilder
func viewForDestination(_ destination: Screen) -> some View {
switch destination {
case .profile:
ProfileView()
case .activeJobs:
ActiveJobsView()
case .offers:
OffersView()
case .message:
ChatView()
}
}
@ViewBuilder
func viewForJob(_ job: Job) -> some View {
PostDetailView(
job: job,
jobUserDetailsRepository: container.makeJobUserDetailsRepository()
)
}
@ViewBuilder
func viewForProfileSubview(_ destination: ProfileView.ProfileSubviews) -> some View {
switch destination{
case .personalSettings:
PersonalSettingView()
case .historicData:
HistoricDataView()
case .transactions:
TransactionView()
case .helpCenter:
HelpcenterView()
case .helpContract:
HelpContractView()
}
}
enum HomeBarDestinations: Hashable, Identifiable {
case postJob
case jobPosting
var id: Self { self }
}
@ViewBuilder
func viewForHomeBar(_ destination: HomeBarView.HomeBarDestinations) -> some View {
switch destination {
case .postJob:
PostJobView()
}
}
}
import Apollo
import FikserAPI
import SwiftData
class DependencyContainer {
static var shared: DependencyContainer!
private let modelContainer: ModelContainer
static func initialize(with modelContainer: ModelContainer) {
shared = DependencyContainer(modelContainer: modelContainer)
}
private init(modelContainer: ModelContainer) {
self.modelContainer = modelContainer
print("DependencyContainer being initialized at ")
}
@MainActor
private lazy var userData: UserData = {
return UserData(apollo: Network.shared.apollo)
}()
@MainActor
private lazy var userDetailsRepository: UserDetailsRepository = {
return UserDetailsRepository(userData: makeUserData())
}()
@MainActor
private lazy var jobData: JobData = {
return JobData(apollo: Network.shared.apollo)
}()
@MainActor
private lazy var jobRepository: JobRepository = {
return JobRepository(jobData: makeJobData(), modelContainer: modelContainer)
}()
@MainActor
func makeUserData() -> UserData {
return userData
}
@MainActor
func makeUserDetailsRepository() -> UserDetailsRepository {
return userDetailsRepository
}
@MainActor
func makeStartupManager() -> StartupManager {
return StartupManager(
userDetailsRepository: makeUserDetailsRepository(),
jobRepository: makeJobRepository(),
authManager: AuthenticationManager.shared,
lastUpdateRepository: makeLastUpdateRepository()
)
}
@MainActor
func makeJobData() -> JobData {
return jobData
}
@MainActor
func makeJobRepository() -> any JobRepositoryProtocol {
return jobRepository
}
@MainActor
private lazy var jobUserData: JobUserData = {
return JobUserData(apollo: Network.shared.apollo)
}()
@MainActor
private lazy var jobUserDetailsRepository: JobUserDetailsRepository = {
return JobUserDetailsRepository(jobUserData: makeJobUserData())
}()
@MainActor
func makeJobUserData() -> JobUserData {
return jobUserData
}
@MainActor
func makeJobUserDetailsRepository() -> JobUserDetailsRepository {
return jobUserDetailsRepository
}
@MainActor
private lazy var lastUpdateData: LastUpdateData = {
return LastUpdateData(apollo: Network.shared.apollo)
}()
@MainActor
private lazy var lastUpdateRepository: LastUpdateRepository = {
return LastUpdateRepository(lastUpdateData: makeLastUpdateData())
}()
@MainActor
func makeLastUpdateData() -> LastUpdateData {
return lastUpdateData
}
@MainActor
func makeLastUpdateRepository() -> LastUpdateRepository {
return lastUpdateRepository
}
}```
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Hi,
I have received the following report after app termination. I have researched online but cannot determine the root cause. Any tips or ideas would help please.
Could it be Location Services, UserNotification Services, or Network Requests?
Thank you,
Brendan
Translated Report (Full Report Below)
Incident Identifier: 6CD59A17-15B1-4F4E-AE84-0286F22893A4
CrashReporter Key: 3d12fb7359053239708afd24c7eed0267a9cc601
Hardware Model: iPhone13,3
Process: AnchorNet3 [5605]
Path: /private/var/containers/Bundle/Application/5EA7F893-D562-45B8-8995-5EAB15F85A7E/AnchorNet3.app/AnchorNet3
Identifier: com.sailsecrets.AnchorNet3
Version: 3.17 (3.17)
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: com.sailsecrets.AnchorNet3 [1443]
Date/Time: 2025-02-06 00:12:03.6136 +0100
Launch Time: 2025-02-05 22:11:19.4220 +0100
OS Version: iPhone OS 18.2 (22C5131e)
Release Type: Beta
Baseband Version: 5.20.03
Report Version: 104
Exception Type: EXC_RESOURCE (SIGKILL)
Exception Codes: 0x0000000000020000, 0x0000000000000000
Termination Reason: PORT_SPACE 14123288431434006528 (Limit 131072 ports) Exceeded system-wide per-process Port Limit
Triggered by Thread: 3
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0:
0 libsystem_kernel.dylib 0x1e27414e4 kevent_id + 8
1 libdispatch.dylib 0x198f51b40 _dispatch_kq_poll + 228
2 libdispatch.dylib 0x198f51080 _dispatch_event_loop_poke + 340
3 QuartzCore 0x192d4631c CA::Context::commit_transaction(CA::Transaction*, double, double*) + 17164
4 QuartzCore 0x192cb8d58 CA::Transaction::commit() + 648
5 QuartzCore 0x192cb8764 CA::Transaction::flush_as_runloop_observer(bool) + 88
6 UIKitCore 0x193a3fd14 _UIApplicationFlushCATransaction + 52
7 UIKitCore 0x193a3d1e0 __setupUpdateSequence_block_invoke_2 + 332
8 UIKitCore 0x193a3d054 UIUpdateSequenceRun + 84
9 UIKitCore 0x193a3f984 schedulerStepScheduledMainSection + 172
10 UIKitCore 0x193a3d5a0 runloopSourceCallback + 92
11 CoreFoundation 0x1911f1f3c CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 28
12 CoreFoundation 0x1911f1ed0 __CFRunLoopDoSource0 + 176
13 CoreFoundation 0x1911f4b30 __CFRunLoopDoSources0 + 244
14 CoreFoundation 0x1911f3d2c __CFRunLoopRun + 840
15 CoreFoundation 0x191246274 CFRunLoopRunSpecific + 588
16 GraphicsServices 0x1de34d4c0 GSEventRunModal + 164
17 UIKitCore 0x193d8f480 -[UIApplication run] + 816
18 UIKitCore 0x1939b5410 UIApplicationMain + 340
19 SwiftUI 0x195b43e30 closure #1 in KitRendererCommon(:) + 168
20 SwiftUI 0x195b43d60 runApp(:) + 100
21 SwiftUI 0x195b43c44 static App.main() + 180
22 AnchorNet3.debug.dylib 0x1025e97bc static MainApp.$main() + 40
23 AnchorNet3.debug.dylib 0x1025eaacc __debug_main_executable_dylib_entry_point + 12
24 dyld 0x1b7352de8 start + 2724
Thread 1 name: com.apple.CoreMotion.MotionThread
Thread 1:
0 libsystem_kernel.dylib 0x1e2741788 mach_msg2_trap + 8
1 libsystem_kernel.dylib 0x1e2744e98 mach_msg2_internal + 80
2 libsystem_kernel.dylib 0x1e2744db0 mach_msg_overwrite + 424
3 libsystem_kernel.dylib 0x1e2744bfc mach_msg + 24
4 CoreFoundation 0x1911f47f4 __CFRunLoopServiceMachPort + 160
5 CoreFoundation 0x1911f3ea0 __CFRunLoopRun + 1212
6 CoreFoundation 0x191246274 CFRunLoopRunSpecific + 588
7 CoreFoundation 0x191259814 CFRunLoopRun + 64
8 CoreMotion 0x19e89cc5c 0x19e88d000 + 64604
9 libsystem_pthread.dylib 0x21bcfb7d0 _pthread_start + 136
10 libsystem_pthread.dylib 0x21bcfb480 thread_start + 8
Thread 2 name: com.apple.uikit.eventfetch-thread
Thread 2:
0 libsystem_kernel.dylib 0x1e2741788 mach_msg2_trap + 8
1 libsystem_kernel.dylib 0x1e2744e98 mach_msg2_internal + 80
2 libsystem_kernel.dylib 0x1e2744db0 mach_msg_overwrite + 424
3 libsystem_kernel.dylib 0x1e2744bfc mach_msg + 24
4 CoreFoundation 0x1911f47f4 __CFRunLoopServiceMachPort + 160
5 CoreFoundation 0x1911f3ea0 __CFRunLoopRun + 1212
6 CoreFoundation 0x191246274 CFRunLoopRunSpecific + 588
7 Foundation 0x18fdc8338 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212
8 Foundation 0x18ff24e24 -[NSRunLoop(NSRunLoop) runUntilDate:] + 64
9 UIKitCore 0x193e22a74 -[UIEventFetcher threadMain] + 420
10 Foundation 0x18feb4194 NSThread__start + 724
11 libsystem_pthread.dylib 0x21bcfb7d0 _pthread_start + 136
12 libsystem_pthread.dylib 0x21bcfb480 thread_start + 8
Thread 3 name: com.apple.SwiftUI.AsyncRenderer
Thread 3 Crashed:
0 libsystem_kernel.dylib 0x1e274162c _kernelrpc_mach_port_allocate_trap + 8
1 libsystem_kernel.dylib 0x1e2748478 mach_port_allocate + 36
2 QuartzCore 0x192d4552c CA::Context::commit_transaction(CA::Transaction*, double, double*) + 13596
3 QuartzCore 0x192cb8d58 CA::Transaction::commit() + 648
4 QuartzCore 0x192cb8764 CA::Transaction::flush_as_runloop_observer(bool) + 88
5 CoreFoundation 0x19119f894 CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 36
6 CoreFoundation 0x19119f3e8 __CFRunLoopDoObservers + 552
7 CoreFoundation 0x1912462c0 CFRunLoopRunSpecific + 664
8 Foundation 0x18fdc8338 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212
9 Foundation 0x18fdc4500 -[NSRunLoop(NSRunLoop) run] + 64
10 SwiftUI 0x195c276d8 specialized static DisplayLink.asyncThread(arg:) + 792
11 SwiftUI 0x195c273a8 @objc static DisplayLink.asyncThread(arg:) + 72
<>
When I install my application, it installs fine and everything works alongwith all the system level daemons but when I reboot the system, none of my daemons are getting launched and this happens only on MacOS 15x, on older version it is working fine.
In the system logs, I see that my daemons have been detected as legacy daemons by backgroundtaskmanagementd with Disposition [enabled, allowed, visible, notified]
2025-01-13 21:17:04.919128+0530 0x60e Default 0x0 205 0 backgroundtaskmanagementd: [com.apple.backgroundtaskmanagement:main] Type: legacy daemon (0x10010)
2025-01-13 21:17:04.919128+0530 0x60e Default 0x0 205 0 backgroundtaskmanagementd: [com.apple.backgroundtaskmanagement:main] Flags: [ legacy ] (0x1)
2025-01-13 21:17:04.919129+0530 0x60e Default 0x0 205 0 backgroundtaskmanagementd: [com.apple.backgroundtaskmanagement:main] Disposition: [enabled, allowed, visible, notified] (0xb)
But later, it backgroundtaskmanagementd decides to disallow it.
2025-01-13 21:17:05.013202+0530 0x32d Default 0x4d6 89 0 smd: (BackgroundTaskManagement) [com.apple.backgroundtaskmanagement:main] getEffectiveDisposition: disposition=[enabled, disallowed, visible, notified], have LWCR=true
2025-01-13 21:17:05.013214+0530 0x32d Error 0x0 89 0 smd: [com.apple.xpc.smd:all] Legacy job is not allowed to launch: <private> status: 2
Is there anything changed in latest Mac OS which is causing this issue? Also what does this status 2 means. Can someone please help with this error?
The plist has is true
When I run my app with XCode on my iPhone, and then moved into the background, I'm getting a EXC_BREAKPOINT exception after a few minutes, seemingly when iOS attempts to call my app with a BGAppRefreshTask:
Thread 23 Queue: com.apple.BGTaskScheduler (com.mycompany.MyApp.RefreshTask) (serial)
0 _dispatch_assert_queue_fail
12 _pthread_wqthread
Enqueued from com.apple.duet.activityscheduler.client.xpcqueue (Thread 23)
0 dispatch_async
20 start_wqthread
I can't quite understand the reason from this crash. In the background task, I'm attempting to update live activities. In the process, it might encounter code that calls MainActor and manipulate @Observable objects. Might that be the reason?
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Swift
Background Tasks
Observation
Purpose
I want to use launchd to run a shell script asynchronously every minute, but I'm encountering an issue where the job does not run, and I receive the error "Bootstrap failed: 5: Input/output error". I need help identifying the cause of this issue and how to configure launchd correctly.
What I've done
Created the shell script (test_ls_save.sh)
The script is designed to list the contents of the desktop and save the output to a specified directory.
#!/bin/bash
DATE=$(date +%Y-%m-%d_%H-%M-%S)
SAVE_DIR=/Users/test/Desktop/personal/log_gather
FILE_NAME="ls_output_$DATE.log"
ls ~/Desktop > "$SAVE_DIR/$FILE_NAME"
echo "ls output saved to $SAVE_DIR/$FILE_NAME"
File permissions (ls -l output): -rwxr-xr-x 1 test staff 1234 Feb 17 10:00 /Users/test/Desktop/personal/log_gather/exec/test_ls_save.sh
Created the launchd plist file (com.test.logTest.plist)
The plist file is configured to execute the shell script every minute.
<key>Label</key>
<string>com.test.logTest</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>-c</string>
/Users/test/Desktop/personal/log_gather/exec/test_ls_save.sh
</array>
<key>StartInterval</key>
<integer>60</integer> <!-- Run every minute -->
File permissions (ls -l output): -rwxr-xr-x 1 test staff 512 Feb 17 10:00 /Users/test/Library/LaunchAgents/com.test.logTest.plist
Ran the job with launchctl
I used the following command to load the plist file into launchd:
sudo launchctl bootstrap gui/$(id -u) /Users/test/Library/LaunchAgents/com.test.logTest.plist
pc spec
MacBook Pro
Apple M1
16 GB RAM
macOS 15.3 (Build 24D60)
what I know
The configuration has been set, but the launchd job is not running every minute as expected.
I don't believe there is a mistake with the path.
When I check the job using launchctl list, the job does not appear in the list.
I don't know where the error log files are supposed to be. I checked /var/log/system.log, but there are no error logs.
The .sh file runs fine by itself, but it cannot be executed via launchctl.
Want to ask
What could be the cause of the launchd job not running as expected?
Also, is there a way to check where the logs are being output?
If there is an error in the plist file configuration, which part should be modified?
Specifically, what improvements should be made regarding environment variables and path settings?
If my information is not enough, please tell me what is not enough!
I have an app that I'm using for my own purposes and is not in the app store. I would like to run an http server in the background for more than the allotted 3 minutes to allow persistent communications with a connected Bluetooth device. The Bluetooth device would poll the service at intervals. Is this possible to do? This app does not need app store approval since it's only for personal use.
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Foundation
IOBluetooth
Core Bluetooth
I understand that GCD and it's underlying implementations have evolved over time. And many things have not been shared explicitly in Apple documentation.
The most concepts of DispatchQueue (serial and concurrent queues), DispatchQoS, target queue and system provided queues: main and globals etc.
I have some doubts & questions to clarify:
[Main Dispatch Queue] [Link] Because the main queue doesn't behave entirely like a regular serial queue, it may have unwanted side-effects when used in processes that are not UI apps (daemons). For such processes, the main queue should be avoided. What does it mean? Can you elaborate?
[Global Concurrent Dispatch Queues] Are they global to a process or across processes on a device. I believe it is the first case but just wanted to be sure.
[Global Concurrent Dispatch Queues] Does system create 4 (for each QoS) * 2 (over-commiting and non-overcommiting queues) = 8 queues in all. When does which type of queue comes into play?
[Custom Queue][Target Queue concept] [swift-corelibs-libdispatch/man/dispatch_queue_create.3] QUOTE The default target queue of all dispatch objects created by the application is the default priority global concurrent queue. UNQUOTE Is this stil true?
We could not find a mention of this in any latest official apple documentation (though some old forum threads (one more) and github code documentation indicate the same).
The official documentation only says:
[dispatch_set_target_queue] QUOTE If you want the system to provide a queue that is appropriate for the current object UNQUOTE
[dispatch_queue_create_with_target] QUOTE Specify DISPATCH_TARGET_QUEUE_DEFAULT to set the target queue to the default type for the current dispatch queue.UNQUOTE
[Dispatch>DispatchQueue>init] QUOTE Specify DISPATCH_TARGET_QUEUE_DEFAULT if you want the system to provide a queue that is appropriate for the current object. UNQUOTE
What is the difference between passing target queue as 'nil' vs 'DISPATCH_TARGET_QUEUE_DEFAULT' to DispatchQueue init?
[Custom Queue][Target Queue concept] [dispatch_set_target_queue] QUOTE The system doesn't allocate threads to the dispatch queue if it has a target queue, unless that target queue is a global concurrent queue. UNQUOTE
The system does allocate threads to the custom dispatch queues that have global concurrent queue as the default target.
What does that mean? Why does targetting to global concurrent queues mean in that case?
[System / GCD Thread Pool] that excutes work items from DispatchQueue: Is this thread pool per queue? or across queues per process? or across processes per device?
MacOS Version: 14.7.2
macOS SDKs:
macOS 14.5 -sdk macosx14.5
I am working on a sample program for validation Against:
Team Identifier
Developer ID
I started with validating Team Identifier, but my validation is not working and it is allowing to launch programs which are not matching the team identifier in the signature.
Below is my code:
func verifyExecutableWithLCR(executablePath: String, arguments: [String]) -> Bool {
let task = Process()
task.launchPath = executablePath
task.arguments = arguments
if #available(macOS 14.4, *) {
print("launchRequirementData is available on this system.")
do {
let req = try OnDiskCodeRequirement.allOf {
TeamIdentifier("ABCDEFGHI")
//SigningIdentifier("com.***.client.***-Client.****")
}
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
let requirementData = try encoder.encode(req)
task.launchRequirementData = requirementData
print("launchRequirementData is set.")
try task.run()
print("[SUCCESS] Executable passed the code signature verification.")
return true
} catch {
print("[ERROR] Code signature verification failed: \(error.localizedDescription)")
return false
}
} else {
print("[WARNING] launchRequirement is not available on this macOS version.")
return false
}
}
Could you please help me in identifying whay am I doing wrong here?
I'm using libxpc in a C server and Swift client. I set up a code-signing requirement in the server using xpc_connection_set_peer_code_signing_requirement(). However, when the client doesn't meet the requirement, the server just closes the connection, and I get XPC_ERROR_CONNECTION_INTERRUPTED on the client side instead of XPC_ERROR_PEER_CODE_SIGNING_REQUIREMENT, making debugging harder.
What I want:
To receive XPC_ERROR_PEER_CODE_SIGNING_REQUIREMENT on the client when code-signing fails, for better debugging.
What I’ve tried:
Using xpc_connection_set_peer_code_signing_requirement(), but it causes the connection to be dropped immediately.
Questions:
Why does the server close the connection without sending the expected error?
How can I receive the correct error on the client side?
Are there any other methods for debugging code-signing failures with libxpc?
Thanks for any insights!
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
XPC
Signing Certificates
Code Signing
Hello,
I recently implemented a conditional debounce publisher using Swift's Combine.
If a string with a length less than 2 is passed, the event is sent downstream immediately without delay. If a string with a length of 2 or more is passed, the event is emitted downstream with a 0.2-second delay.
While writing test logic related to this, I noticed a strange phenomenon: sometimes the publisher, which should emit events with a 0.2-second delay, does not emit an event.
The test code below should have all indices from 1 to 100 in the array, but sometimes some indices are missing, causing the assertion to fail. Even after observing completion, cancel, and output events through handleEvents, I couldn't find any cause. Am I using Combine incorrectly, or is there a bug in Combine?
I would appreciate it if you could let me know.
import Foundation
import Combine
var cancellables: Set<AnyCancellable> = []
@MainActor func text(index: Int, completion: @escaping () -> Void) {
let subject = PassthroughSubject<String, Never>()
let textToSent = "textToSent"
subject
.map { text in
if text.count >= 2 {
return Just<String>(text)
.delay(for: .seconds(0.2), scheduler: RunLoop.main)
.eraseToAnyPublisher()
} else {
return Just<String>(text)
.eraseToAnyPublisher()
}
}
.switchToLatest()
.sink {
if $0.count >= 2 {
completion()
}
}.store(in: &cancellables)
for i in 0..<textToSent.count {
let stringIndex = textToSent.index(textToSent.startIndex, offsetBy: i)
let stringToSent = String(textToSent[textToSent.startIndex...stringIndex])
subject.send(stringToSent)
}
}
var array = [Int]()
for i in 1...100 {
text(index: i) {
array.append(i)
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
for i in 1...100 {
assert(array.contains(i))
}
}
RunLoop.main.run(until: .now + 10)
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:
DevForums 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 DevForums post
Validating Signature Of XPC Process DevForums post
This DevForums post summarises the options for bidirectional communication
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 a weird issue with our Endpoint Security extension.
A couple of the checks we do require calling into Apple frameworks (Security, Disk Arbitration) and these checks can happen early in the boot process. On macOS 13 (and possibly earlier), sometimes these calls get stuck and never return. When this happens, the kernel will kill the extension and this generates a crash log. This adds significant time to the boot, enough that people notice. In every case, the thread where the call into the Apple framework occurred shows that the thread is stuck in mach_msg2_trap(), which I now understand means it's likely waiting on an event or message.
Now here's where things get weird. I discovered that if I shunt the check off onto a Thread subclass and put it in a DispatchGroup (perhaps the wrong primitive), then wait() on that group with my own timeout, the thread will get unstuck within a couple hundred milliseconds of the timeout. The timeout can be a couple of seconds or longer. In every case, the thread unblocks, returns from mach_msg2_trap() and the original call finishes as expected.
Is there a rational explanation for this behavior? Am I crazy to even consider shipping this workaround?