How to detect when a process starts up on macOS?

Solution 1:

Create the App

Open this in Script Editor and export it as a read-only application and make sure stay open after run handler is off

After exporting follow this guide to prevent it from show up in the dock.

# Block Apps By Josh Brown
# Last Modified: Aug 23 2018
global applist

on run
    set applist to {"Google Chrome", "App Store"} -- Apps to limit
    if checkapps() then
        killall()
    end if
end run
on is_running(appName)
    try
        if (the length of (do shell script "pgrep -x " & quoted form of appName) > 0) then
            kill(do shell script "pgrep -x " & quoted form of appName)
        end if
    end try
end is_running

on checkapps()
    set x to false
    repeat with a from 1 to length of applist
        is_running(item a of applist)
    end repeat
    return x
end checkapps

on kill(theID)
    do shell script "kill -9 " & theID
end kill

Create the LaunchDaemon

Note: You must be an admin to do this.

Save the following file to /Library/LaunchDaemons/

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.PlzUpvoteMy.answer</string>
        <key>ProgramArguments</key>
        <array>
            <string>/usr/bin/open</string>
            <string>-W</string>
            <string>**/path/to/application.app**</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>StartInterval</key>
        <integer>5</integer>
        <key>UserName</key>
        <string>**UserToBlock**</string>
    </dict>
</plist>

Change the permissions with the following command:

sudo chown root:wheel /Library/LaunchDaemons/com.MyName.plist

Load the Daemon

Note: You must be admin to do this.

To start the daemon use this command:

sudo launchctl load /Library/LaunchDaemons/com.MyName.plist 

The program will scan for the apps every 5 seconds and close them if they are running.

To stop the Daemon use this command

sudo launchctl unload /Library/LaunchDaemons/com.MyName.plist