在 ubuntu 16.04 上创建守护进程

Jua*_*rés 15 ubuntu daemon ubuntu-16.04

我用 PHP 开发了一个爬虫,它解析一个带有特定标头的 URL,并将所有内容的 URL 放入队列中。它工作正常。

我在 ubuntu 14.04 中开发了这段代码,并在 /etc/init 文件夹中放置了一个 .conf 文件,其中包含以下内容:

# Info
description "Warm the varnish to get the list of products"
author      "Juanjo Aguilella"

# Events
start on startup
stop on shutdown

# Automatically respawn
respawn
respawn limit 100 5

# Run the script
# Note, in this example, if your PHP script return
# the string "ERROR", the daemon will stop itself.
script
    [ $(exec /usr/bin/php -f /var/www/crawler.php) = 'ERROR' ] && ( stop; exit 1; )  
end script
Run Code Online (Sandbox Code Playgroud)

它在 Ubuntu 14.04 中运行良好,我可以使用“sudo service crawler start”和“sudo service crawler stop”启动和停止守护进程

现在在生产环境中,我有一个 Ubuntu 16.04 服务器,我将相同的代码放在同一个文件夹中,但是当我尝试启动该服务时,我收到消息“无法启动 crawler.service。未找到 Unit crawler.service”

你能给我任何帮助吗?

问候

小智 15

添加到@Juanjo Aguilella Marés 的回答中,一旦您将脚本复制/链接到/etc/systemd/system,您可能希望在服务器启动时自动启动它:

sudo systemctl daemon-reload
sudo systemctl enable my_service.service
sudo systemctl start my_service.service
Run Code Online (Sandbox Code Playgroud)

数字海洋

最好不要以 root 身份运行它。只需更改user脚本中的行:

[Service]
User=some_user
Run Code Online (Sandbox Code Playgroud)


Jua*_*rés 13

我解决了这个问题:

a) 使用以下代码在 /etc/systemd/system 中创建文件 crawler.service:

[Unit]
Description=Crawler cache Service
After=network.target

[Service]
User=root
Restart=always
Type=forking
ExecStart=/var/www/execute.sh

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

我的 bash 文件包含与此代码相同的 php 文件并行的不同执行:

#!/bin/sh
php /var/www/tiendas.local.mediamarkt.es/crawler.php
sleep 0.1
{
    php /var/www/tiendas.local.mediamarkt.es/crawler.php
}&
sleep 0.2
{
    php /var/www/tiendas.local.mediamarkt.es/crawler.php
}&
sleep 0.3
{
    php /var/www/tiendas.local.mediamarkt.es/crawler.php
}&
sleep 0.4
{
    php /var/www/tiendas.local.mediamarkt.es/crawler.php
}
Run Code Online (Sandbox Code Playgroud)

执行之间的睡眠是解决服务执行速度如此之快的问题所必需的。

如果您对解决方案有任何建议,请发表评论,我在 bash 文件和 systemd 文件方面没有很多经验,但目前工作正常。


use*_*517 5

14.04 的初始化系统是新贵。16.04 的初始化系统是 systemd。您应该将新贵脚本转换为 systemd单元文件。还有很多其他资源可用。