Shahar
Shahar

Reputation: 501

Centos 7 Created service to run shell script on infinite loop

I have the following script:

whie true
do
  #code
sleep 60
done

I then wanted to create a service to start the machine and launch this script as service: created my.service at /etc/systemd/system/my.service

[Unit]
Description=my Script

[Service]
Type=forking
ExecStart=/bin/script.sh

[Install]
WantedBy=multi-user.target

problem occurs when i systemctl start my.service

it goes to while true loop and hang in there, how can i run this service and make it run in the background ?

Upvotes: 0

Views: 406

Answers (1)

nhatnq
nhatnq

Reputation: 1193

According to systemd specification at link. Type=forking is not exactly correct kind of start-up in your case

If set to forking, it is expected that the process configured with ExecStart= will call fork() as part of its start-up. The parent process is expected to exit when start-up is complete and all communication channels are set up. The child continues to run as the main service process, and the service manager will consider the unit started when the parent process exits. This is the behavior of traditional UNIX services. If this setting is used, it is recommended to also use the PIDFile= option, so that systemd can reliably identify the main process of the service. systemd will proceed with starting follow-up units as soon as the parent process exits.

The Type=simple can be correct one. You can try with it

If set to simple (the default if ExecStart= is specified but neither Type= nor BusName= are), the service manager will consider the unit started immediately after the main service process has been forked off. It is expected that the process configured with ExecStart= is the main process of the service. In this mode, if the process offers functionality to other processes on the system, its communication channels should be installed before the service is started up (e.g. sockets set up by systemd, via socket activation), as the service manager will immediately proceed starting follow-up units, right after creating the main service process, and before executing the service's binary. Note that this means systemctl start command lines for simple services will report success even if the service's binary cannot be invoked successfully (for example because the selected User= doesn't exist, or the service binary is missing).

Upvotes: 1

Related Questions