How to start script as root with DISPLAY=:0

I have a script should run with root privileges and also should use display(opencv imshow in it.) How can I run that script at reboot?

I tried with a my.sh file:

export DISPLAY=:0
/usr/bin/python3 /path/to/myscript.py

cronjob:

@reboot /bin/bash /path/to/my.sh

Yet it doesnt start.

Can you please help me?


Solution 1:

You cannot run a job that is run @reboot with a graphical display because at the moment the system boots, there is no graphical display up and running yet.

You should add that script to "Startup programs" of your desktop session. As for running as root, the most foolproof method of running a script as root for me is to use a binary wrapper that is setuid root.

Write a following short C program (call it wrapper.c for example):

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
   int rc;
   setuid( 0 );
   rc=WEXITSTATUS(system( "/path/to/your/script" ));
   exit(rc);
}

Compile the program using: gcc -o wrapper wrapper.c (you need to have build-essential package installed for that).

Make the wrapper file setuid root: sudo chown root:root wrapper followed by sudo chmod o+s wrapper

Then configure path to your wrapper file into startup programs of your desktop session.