Run the "launchctl" command as a specific user using NSTask in OS X

My application runs as root, and I need to be able to offload processes using NSTask and launchctl. Here is the code I'm doing:

    NSPipe *pipe = [NSPipe pipe];

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/launchctl"];
    [task setCurrentDirectoryPath:@"/"];
    [task setStandardError:pipe];

    NSLog(@"/bin/launchctl unload %@", plistAutostartLocation);

    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: enableCommand, plistAutostartLocation, nil];
    [task setArguments: arguments];

    NSFileHandle * read = [pipe fileHandleForReading];

    [task launch];
    [task waitUntilExit];

If the process needs to be unloaded, it starts as "root", then it is unloaded successfully, if not a failure. The question is how to launch "launchctl" as a specific user (for example, "myusername")?

Edit: In the terminal, if I want to run some command under a specific user, I do the following and it works well:

su - myusername -c "ls / Users / myusername"

But when I try to run "launchctl" under a specific user, it fails:

su - myusername -c "launchctl load/Library/LaunchAgents/com.google.keystone.agent.plist"

: " "

+4
1

, . , Apple:

-GUI bootstrap namespaces. GUI GUI (loginwindow WindowServer) GUI. -GUI , SSH. , GUI, Dock, GUI .

su bootsrap, launchd.

, , , :

  • 10.10 : launchctl asuser. , <myusername>. , root, . :

     launchctl asuser <myusername> launchctl load "/Library/LaunchAgents/com.google.keystone.agent.plist"
    
  • 10.10 ( 10.11 SIP ): launchctl bsexec. . , UID , :

    launctl bsexec <pid> su -u <myusername> launchctl load "/Library/LaunchAgents/com.google.keystone.agent.plist"
    
+1

Source: https://habr.com/ru/post/1543862/


All Articles