macoslaunchdlaunchctl

How to programmatically start an application at user login?


I am attempting to port a C# Windows application to macOS 12 Monterey for the first time. One of its features was setting up automatic start-up, which in there was done through Windows registry. I have found out that on macOS this is done through launchd/launchctl, so I tried to set it up manually first. I have added a .plist file to the /Library/LaunchAgents folder with the following configuration:

<plist version="1.0">
 <dict>
   <key>Label</key>
   <string>application</string>
   <key>RunAtLoad</key>
   <true />
   <key>Program</key>
   <string>/Users/user/Desktop/osx-x64/application</string>
  </dict>
</plist>

I tried to enable this configuration through the terminal with launchctl load /Users/user/Library/LaunchAgents/application.plist, however that always throws Load failed: 5: Input/output error. Finding out it is a deprecated function, I tried launchctl kickstart with this file, which is met with Could not find service "application" in domain for user gui: 501. Could this be related to file privileges?

Most of information I find about this refers to no longer existing documentation, so any information on how to achieve the auto-start on Monterey would be appreciated.


Solution

  • The Input/output error means the .plist file you provided is incorrect either in xml way or in target way.

    You can read about all this here, and I will just post some advices, that should help for this specific case. Some of them are not necessary to make this work, but believe me, it is better to stay with them.

    1. Use the full xml header. (example on website above)
    2. The Label value must be the same with the plist file name. It is also almost always a bundle id. So, make it com.my.application.plist, and the value of Label field should be com.my.application
    3. Don't do spaces where they are unneeded, e.g. true/, not true /
    4. The program path should be the path to unix binary. Try, if you can launch your app from terminal using this path /Users/user/Desktop/osx-x64/application If no, you need to fix this at first.

    This should work for you.