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

Issue with launchd Job Not Running – "Bootstrap failed: 5: Input/output error"
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!
1
0
528
Feb ’25
Do i need to free memory for C strings obtained from xpc_dictionary_get_string?
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 # ... # ...
2
0
394
Feb ’25
[MacOS] Accessing underlying pthread or mach thread of NSThread
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)
2
0
304
Feb ’25
XPC Service Cleanup and Freeing Memory
I have used C APIs to create a XPC server(mach service) as a launch daemon. I use dispatch_source_create () followed by dispatch_resume() to start the listener. I dont have any code for cleaning up memory. I want to make sure that the XPC server is shutdown gracefully, without any memory leaks. I know that launchd handles the cycle and the XPC framework takes care of XPC objects. But do I need to do additional cleanup when the XPC listener is shutdown ?
7
0
438
Mar ’25
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
197
Mar ’25
XPC Error: Underlying connection interrupted
Im using the low-level C xpc api <xpc/xpc.h> and i get this error when I run it: Underlying connection interrupted. I know this error stems from the call to xpc_session_send_message_with_reply_sync(session, message, &reply_err);. I have no previous experience with xpc or dispatch and I find the xpc docs very limited and I also found next to no code examples online. Can somebody take a look at my code and tell me what I did wrong and how to fix it? Thank you in advance. Main code: #include <stdio.h> #include <xpc/xpc.h> #include <dispatch/dispatch.h> // the context passed to mainf() struct context { char* text; xpc_session_t sess; }; // This is for later implementation and the name is also rudimentary void mainf(void* c) { //char * text = ((struct context*)c)->text; xpc_session_t session = ((struct context*)c)->sess; dispatch_queue_t messageq = dispatch_queue_create("y.ddd.main", DISPATCH_QUEUE_SERIAL); xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); xpc_dictionary_set_string(message, "test", "eeeee"); if (session == NULL) { printf("Session is NULL\n"); exit(1); } __block xpc_rich_error_t reply_err = NULL; __block xpc_object_t reply; dispatch_sync(messageq, ^{ reply = xpc_session_send_message_with_reply_sync(session, message, &reply_err); if (reply_err != NULL) printf("Reply Error: %s\n", xpc_rich_error_copy_description(reply_err)); }); if (reply != NULL) printf("Reply: %s\n", xpc_dictionary_get_string(reply, "test")); else printf("Reply is NULL\n"); } int main(int argc, char* argv[]) { // Create seperate queue for mainf() dispatch_queue_t mainq = dispatch_queue_create("y.ddd.main", DISPATCH_QUEUE_CONCURRENT); dispatch_queue_t xpcq = dispatch_queue_create("y.ddd.xpc", NULL); // Create the context being sent to mainf struct context* c = malloc(sizeof(struct context)); c->text = malloc(sizeof("Hello")); strcpy(c->text, "Hello"); xpc_rich_error_t sess_err = NULL; xpc_session_t session = xpc_session_create_xpc_service("y.getFilec", xpcq, XPC_SESSION_CREATE_INACTIVE, &sess_err); if (sess_err != NULL) { printf("Session Create Error: %s\n", xpc_rich_error_copy_description(sess_err)); xpc_release(sess_err); exit(1); } xpc_release(sess_err); xpc_session_set_incoming_message_handler(session, ^(xpc_object_t message) { printf("message recieved\n"); }); c->sess = session; xpc_rich_error_t sess_ac_err = NULL; xpc_session_activate(session, &sess_ac_err); if (sess_err != NULL) { printf("Session Activate Error: %s\n", xpc_rich_error_copy_description(sess_ac_err)); xpc_release(sess_ac_err); exit(1); } xpc_release(sess_ac_err); xpc_retain(session); dispatch_async_f(mainq, (void*)c, mainf); xpc_release(session); dispatch_main(); } XPC Service code: #include <stdio.h> #include <xpc/xpc.h> #include <dispatch/dispatch.h> int main(void) { xpc_rich_error_t lis_err = NULL; xpc_listener_t listener = xpc_listener_create("y.getFilec", NULL, XPC_LISTENER_CREATE_INACTIVE, ^(xpc_session_t sess){ printf("Incoming Session: %s\n", xpc_session_copy_description(sess)); xpc_session_set_incoming_message_handler(sess, ^(xpc_object_t mess) { xpc_object_t repl = xpc_dictionary_create_empty(); xpc_dictionary_set_string(repl, "test", "test"); xpc_rich_error_t send_repl_err = xpc_session_send_message(sess, repl); if (send_repl_err != NULL) printf("Send Reply Error: %s\n", xpc_rich_error_copy_description(send_repl_err)); }); xpc_rich_error_t sess_ac_err = NULL; xpc_session_activate(sess, &sess_ac_err); if (sess_ac_err != NULL) printf("Session Activate: %s\n", xpc_rich_error_copy_description(sess_ac_err)); }, &lis_err); if (lis_err != NULL) { printf("Listener Error: %s\n", xpc_rich_error_copy_description(lis_err)); xpc_release(lis_err); } xpc_rich_error_t lis_ac_err = NULL; xpc_listener_activate(listener, &lis_ac_err); if (lis_ac_err != NULL) { printf("Listener Activate Error: %s\n", xpc_rich_error_copy_description(lis_ac_err)); xpc_release(lis_ac_err); } dispatch_main(); }
1
0
300
Mar ’25
Background Audio Recording
I have an app that uses background audio recording. From what others say, I have enabled the audio background mode to keep the audio session active, and this worked. But when submitting the app to the app store, the app was rejected because the audio background mode is only supposed to be used for audio playback. How do I create this background mode while following Apple's guidelines?
3
0
119
Apr ’25
BGProcessingTask File Upload Limits
I have BGProcessingTask & BGAppRefreshTask working fine. The main purpose of my use of BGProcessingTask is to upload a file to AWS S3 using multipart/form-data. I have found that any file above about 2.5MB times out after running almost four minutes. If I run the same RESTful api using curl or Postman, I can upload a 25MB file in 3 seconds or less. I have tried to deliberately set .earliestBeginDate to 01:00 or 02:00 local time on the iPhone, but that does not seem to help. I use the delegate (yes, I am writing in Objective C) - URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: and find that the iOS system uploads about 140kB every 15 seconds or so. I am looking for recommendations or insight into how I might enable uploads of 25MB files. I would be happy it I could do just one a day for my use case. I provide code on how I set up the NSURLSession and NSURLSessionDownloadTask, as it is my guess that if there is something that needs to be modified it is there. I have to believe there is a solution for this since I read in many posts here and in StackOverflow how developers are using this functionality for uploading many, many files. NSURLSessionConfiguration *sConf = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:bkto.taskIdentifier]; sConf.URLCache = [NSURLCache sharedURLCache]; sConf.waitsForConnectivity = YES; sConf.allowsCellularAccess = NO; sConf.networkServiceType = NSURLNetworkServiceTypeVideot; sConf.multipathServiceType = NSURLSessionMultipathServiceTypeNone; sConf.discretionary = YES; sConf.timeoutIntervalForResource = kONEHOURINTERVAL; sConf.timeoutIntervalForRequest = kONEMINUTEINTERVAL; sConf.allowsExpensiveNetworkAccess = NO ; sConf.allowsConstrainedNetworkAccess = NO; sConf.sessionSendsLaunchEvents = YES; myURLSession = [NSURLSession sessionWithConfiguration:sConf delegate:self delegateQueue:nil]; And then later in the code... NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:pth]]; request.HTTPMethod = kHTTPPOST; request.HTTPBody = [NSData my body data]; request.timeoutInterval = 60; [request setValue:@"*/*" forHTTPHeaderField:@"Accept"]; [request setValue:@"en-us,en" forHTTPHeaderField:@"Accept-Language"]; [request setValue:@"gzip, deflate, br" forHTTPHeaderField:@"Accept-Encoding"]; [request setValue:@"ISO-8859-1,utf-8" forHTTPHeaderField:@"Accept-Charset"]; [request setValue:@"600" forHTTPHeaderField:@"Keep-Alive"]; [request setValue:@"keep-alive" forHTTPHeaderField:@"Connection"]; NSString *contType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",bnd]; [request setValue:contType forHTTPHeaderField:@"Content-Type"]; [request addValue:[NSString stringWithFormat:@"%lu",(unsigned long)myData.length] forHTTPHeaderField:@"Content-Length"]; and here are a few lines from my logs to show the infrequent multi-part uploads of only small chunks of data by the iOS system: -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: bytesSent = 393,216 -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: totalBytesSent = 393,216 -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: task = BackgroundDownloadTask <76A81A80-4703-4686-8742-A0048EB65108>.<2>, time Fri Mar 7 16:25:27 2025 -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: bytesSent = 131,072 -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: totalBytesSent = 524,288 -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: task = BackgroundDownloadTask <76A81A80-4703-4686-8742-A0048EB65108>.<2>, time Fri Mar 7 16:25:42 2025 -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: bytesSent = 131,072 -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: totalBytesSent = 655,360 -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: task = BackgroundDownloadTask <76A81A80-4703-4686-8742-A0048EB65108>.<2>, time Fri Mar 7 16:25:56 2025 -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: bytesSent = 131,072 -[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: totalBytesSent = 786,432
5
0
101
Mar ’25
Service Showing "Not Responding" in Activity Monitor Despite Running Threads.
I am encountering an issue with my application, BloxOneEndpoint.pkg, which includes two services: rc_service_infoblox – Runs as the root user. Controller Application – Runs as a normal user. Although a thread within rc_service_infoblox is running fine and performing its expected tasks, I notice that the service appears as "Not Responding" in Activity Monitor. Despite normal functionality, this status is concerning, as it may indicate some issue to customer. I would appreciate any insights into why this might be happening and how to resolve it. Is there a specific API or mechanism I should use to ensure the service remains in a "Running" state in Activity Monitor? Thank you for your guidance.
13
0
158
Apr ’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
57
Mar ’25
SMAppService - How does this work?
I'm a developer using Lazarus Pascal, so converting ObjC and Swift comes with its challenges. I'm trying to figure how to properly use SMAppService to add my application as a login item for the App Store. I have learned that the old method (&lt; macOS 13) uses a helper tool, included in the app bundle, which calls the now deprecated SMLoginItemSetEnabled. Now this is already quite a pain to deal with if you're not using XCode, not to mention converting the headers being rather complicated when you're not experienced with doing this. The "new" method (as of macOS 13) is using SMAppService. Can anyone explain how to use this? The documentation (for me anyway) is a not very clear about that and neither are examples that can be found all over the Internet. My main question is: Can I now use the SMAppService functions to add/remove a login item straight in my application, or is a helper tool still required?
3
0
104
Mar ’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
77
Mar ’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
112
Mar ’25
Background processing question
Hi, I have a hard time getting my head wrapped around the possibilities of running a app or a task in a app in the background. I have a app where I utilize MusicKit to create a playlist in Apple Music, and add songs to the playlist. Now the songs added are picked from choices made by the user, and the total number of songs to add is 75, and that takes some time. And if the user switches to a different app or the phone is locked, the add songs logic stops, and then starts again as soon as the app is active again. What I am trying to achieve is of course for this to keep processing also when the app is not active, so basically to keep it running in the background. But this is where I struggle to understand how I can do that - The available choice seems to be BGTaskScheduler, but that just does not seem correct. From what I understand it just schedules a task, and it will be processed whenever the app or phone "feels like it" (again, my understanding, might be wrong), and that won't work in my scenario. I want the task to start when the user taps a button, and just keep running until it is finished, regardless of if the app is active or not. Any pointers, tips, advices out there on how I can achieve this?
2
0
63
Apr ’25
Launch daemon running but XPC is down
Hello, I have a question about a edge case scenario. Before that some info on my project- I have a launchdaemon that carries out some business logic, it also has XPC listener (built using C APIs). Question- Can there be a situation when the daemon is up and running but the XPC listener is down(due to some error or crash)? If yes then do I need to handle it in my code or launchd will handle it? when the daemon is stopped or shut down, how do I stop the XPC listener? After getting listener object from xpc_connection_create_mach_service should I just call xpc_connection_cancel followed by a call to xpc_release? Thanks! K
3
0
115
Apr ’25
earliestBeginDate timezone
I'm trying to schedule a background task that will run on an iPhone and I'm looking into creating a task request using BGProcessingTaskRequest and scheduled it using BGTaskScheduler.shared.submit(). Per earliestBeginDate documentation, this property can be used to specify the earliest time a background task will be launched by OS. All clear here. However, the question is: how is the value interpreted with respect to timezone ? Is the specified date in device timezone ? Is GMT ? Is something else ?
2
0
54
Apr ’25
Launch Host App from Share Extension
Hi! Could you please point me to the official documentation or recommended approach for launching the host app from a Share Extension? The scenario is: The user is sharing some text to my app. I need launch App and show this text. At the moment, I'm using the following hack: let selector = NSSelectorFromString("sharedApplication") if let app = UIApplication.perform(selector)?.takeUnretainedValue() as? UIApplication, app.responds(to: #selector(UIApplication.open(_:options:completionHandler:))) { app.open(url, options: [:], completionHandler: nil) } This does work, but it's terrible. So, the question: What is the official way to open the host app from within a Share Extension? Thanks!
2
0
113
Apr ’25
Working with Input/Output stream with Swift 6 and concurrency framework
Hello, I am developing an application which is communicating with external device using BLE and L2CAP. I wonder what are the best practices of using Input & Output streams that are established with L2CAP connection when working with Swift 6 concurrency model. I've been trying to find some examples and hints for some time now but unfortunately there isn't much available. One useful thread I've found is: https://developer.apple.com/forums/thread/756281 but it does not offer much insight into using eg. actor model with streams. I wonder if something has changed in this regards? Also, are there any plans to migrate eg. CoreBluetooth stack to new swift 6 concurrency ?
2
0
96
Apr ’25