1

I'm trying to use launchd to solve the above-mentioned.

I have a networkchange.plist file as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" \
 "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>NetworkChange</string>
  <key>LowPriorityIO</key>
  <true/>
  <key>ProgramArguments</key>
  <array>
      <string>*some path*/networkchangeaction.sh</string>
  </array>
  <key>WatchPaths</key>
  <array>
    <string>/etc/resolv.conf</string>
    <string>/var/run/resolv.conf</string>
    <string>/private/var/run/resolv.conf</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

Using sudo launchctl load -w /Library/LaunchDaemons/networkchange.plist after moving it to it's place it executes my bash script just fine when I switch Wi-Fi networks.

My networkchangeaction.sh script:

#!/bin/bash

lock="/tmp/networkchange.lock"
triggerssid="someSSID"
macaddress="7c:c5:d7:f2:09:23"
ssid=$(networksetup -getairportnetwork en0 | awk -F": " '{print $2}')

if mkdir "$lock"; then    # my attempt at solving the infinite call loop
    trap 'sudo rm -rf "$lock"' 0    # $lock is kinda like a mutex
    if [ "$ssid" == "$triggerssid" ]; then
        sudo ifconfig en0 ether $macaddress    # change MAC address
        sudo ifconfig en0 down    # restart wifi interface
        sudo ifconfig en0 up
        sleep 2                   # wait for it to restart, then join $triggerssid
        sudo networksetup -setairportnetwork en0 $triggerssid *wifi wpa2*
    fi
else
    exit 0
fi

My problem is that the script is called infinitely as it rejoins the network after changing the MAC address. I tried solving this with a "mutex" (as recommended here), so that only one instance of this script can run at a time, but somehow it still gets called continuously.

How could I solve this problem, so that the script does not trigger itself?

  • Having the script called continuously (again and again) is different from using a mutex to prevent parallel execution. Which problem are you trying to solve here? – nohillside Feb 16 '17 at 21:13
  • Also I would assume that running ifconfig would change some of the watched files which again triggers the script. – nohillside Feb 16 '17 at 21:15
  • @patrix i clarified the question. the problem certainly is that the script triggers itself. i assumed that launchd calls the script while the first instance is still running and thus i tried the mutex solution. – krispet krispet Feb 16 '17 at 21:39

You must log in to answer this question.

Browse other questions tagged .