Run as service from c++ program

Hi, I'm facing this problem, even if I know it isn't strictly related with node-red itself.
I have installed node-red on debian with the raccomanded script, so I can run it as service.
My problem is that I don't have to start it at boot (so I disabled its service). What I need is to start it from a C++ program., but I cannot find the right command, even because calling it as service it requires the password.
I tryed this command but it works only from comman line, not from within the c++ program

echo psw | sudo -S sudo systemctl start node-red.service

Thanks

Have you already tried

echo psw | sudo -S systemctl start nodered

yes, nothing. The strange thing is that it still shows the string after "echo", so pratically it show (as for your suggestion)

psw | sudo -S systemctl start nodered

The code is:

int main(void){
	char *args[]={(char *)"echo",
				  (char *)"psw",
				  (char *)"|",
				  (char *)"sudo",
				  (char *)"-S",
				  (char *)"sudo",
				  (char *)"systemctl",
				  (char *)"start",
				  (char *)"node-red.service",
					NULL};
	printf("\nstart Nodered...");				
	execvp(args[0],args);
	printf("Nodered running!");
	return 0;
}

First, you need to give the user running the C++ program the authority to run the systemctl command without a password. You can do that using the command sudo visudo and give the user the appropriate permissions by adding something like
the_user ALL=NOPASSWD:/bin/systemctl start nodered.service

Then you can test that by logging on as that user and running
sudo systemctl start nodered.service
and it should not ask for a password.

Second note that it is nodered.service, not node-red.service.

Third, in the command you run it is best to give the full path to systemctl in case the path is not setup in the environment you run the command.

1 Like

Thanks, it helps a lot. OK. Now I have this situation:

  • from command line it works correctly without asking for the password
  • I created a new service different from the default one, this why nodered.service
  • putting the full patch in the command it asks for the password:
    sudo systemctl start /etc/systemd/system/nodered.service
  • without full path
    sudo systemctl start nodered.service
    it works but: the program stops and exit after execute the execvp command. I Don't know if it is normal, but aswell it doesn't print on video the printf line

That is because the command parameters are different to the ones you specified. I meant the full path to the command (systemctl) not the service.

Thanks so much. Solved and working great

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.