0

I'm trying to run a ptyhon script on a raspberry as soon as it reboot so I'm using a cronjob for it. My program has 2 main modules main.py that initializes the listener thread and find_neighbours.py that is a python threading.Thread subclass. This thread must broadcast a message via socket but this does not occur and in the log file I see the following:

Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/home/pi/Proyecto_Rasp/find_neighbours.py", line 52, in run
self.broadcast("First message!")
File "/home/pi/Proyecto_Rasp/find_neighbours.py", line 18, in broadcast
s.sendto(msg, ('<broadcast>', 1234)) error: [Errno 101] Network is unreachable

Here's my .sh

#!/bin/sh
cd /home/pi/my_path
python main.py

I declared the cronjob like:

sudo crontab -e

and added the following lines:

@reboot sh /home/pi/my_bash.sh > /home/pi/path_to_log/log.txt 2>&1

Finally, the problem is in this method:

def broadcast(self, msg):
    s = socket(AF_INET, SOCK_DGRAM)
    s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
    s.sendto(msg, ('<broadcast>', 1234))

What am I doing wrong?

I appreciate any help.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 1
    The script works fine when already booted and not run as a cronjob, correct? If so, you likely need logic to poll for network connectivity. I am not certain *exactly* when `@reboot` scripts are run in the boot process, but it *may* be before the networking stack is initialized on your pi. – Travis Clarke Dec 13 '17 at 02:44
  • This may be helpful also if it is, in fact, a network-related race condition: https://stackoverflow.com/questions/3764291/checking-network-connection – Travis Clarke Dec 13 '17 at 02:49
  • Instead of running the script blindly then waiting for network connection, use systemd's require directive. If using the legacy init scripts, fire it anywhere after network scripts. – alvits Dec 13 '17 at 03:38
  • So should I use systemd instead of crontab? – Sergio Palechor Dec 13 '17 at 04:13

0 Answers0