Search code examples
objective-cmacosxpc

Add commandline target in Xcode the ability to function as XPC server


I currently have target from type commandlined tool that run as daemon using a plist file under /Library/LaunchDaemons.

Now I need add it the functionality to receive XPC messages from another process that I have. This Macho file is standalone and runs under application bundle in Resources subfolder.

I added and implemented the following interface and called it from main method, but it's enough ?

@interface ServiceDelegate : NSObject <NSXPCListenerDelegate>
ServiceDelegate *delegate = [ServiceDelegate new];
    
NSXPCListener *listener = [[NSXPCListener alloc] initWithMachServiceName:@"com.macho.scanner"];
    
[listener resume];
    
[[NSRunLoop mainRunLoop] run];

The question is whether I can modify my command-line target and add an XPC server, or should I need to create new target from type XPC service, and run it as daemon ?

thanks


Solution

  • You should be able to add XPC server to your cmd target.

    It would require two things:

    1. Adding necessary code to run the server. I'm using C API for this, but Objective-C should be pretty the same. I would add to your code at least setting the delegate to the listener.

    2. Declaring in the launch.plist that you want to have some mach service. It looks like:

    <key>MachServices</key>
        <dict>
            <key>com.macho.scanner</key>
            <true/>
        </dict>
    

    Also beware: your daemon runs under root namespace, and namespaces are like stack with the root on bottom. User apps could see your daemon mach endpoint and establish connection to it, but nor vice versa.