作为守护进程启动的 Dotnet 应用程序无法正常工作

Dotnet app started as daemon doesn't working properly

我使用NetCore开发了一个简单的应用程序,应用程序每次执行时都将内容写入一个文件,这是代码:

using System;
using System.IO;

namespace SimpleApp
{
   class Program
   {
       static void Main(string[] args)
       {
          using (StreamWriter writer = new StreamWriter("log.txt", true))
          {
              writer.WriteLine("Hello World");
          }
       }
   }
}

因此,如果我以这种方式启动应用程序:dotnet SimpleApp.dll 我会得到一个 log.txt 文件,其中包含 Hello World

现在,我正在尝试创建一个 linux 守护进程,我没有这方面的经验,所以我写下了我在互联网上学到的东西,我创建了一个服务 cakked console.service 其中包含这个结构:

[Unit]
Description = Hello World Daemon

[Service]
ExecStart = /usr/bin/dotnet /home/my username/Desktop/publish/SimpleApp.dll
Restart = on-failure

[Install]
WantedBy = multi-user.target

基本上我有一个描述,我在 ExecStart 中设置了我的 dotnet 安装路径和应用程序路径。

稍后我有一个 Install,如果理解得很好,我会告诉 systemctl 该服务可以 运行 每个用户,对吗?

后来我把服务复制到system文件夹里:

sudo cp console.service /lib/systemd/system

我启用了它:

sudo systemctl daemon-reload 
sudo systemctl enable console.service

所以,我执行了服务:

sudo systemctl start console.service

当我打印状态时:

systemctl status console.service

将显示为:

问题是文件夹publish里面(ExecStart指定的应用程序路径)我现在没有log.txt

为什么?

由于您只为文件指定了一个相对路径,它将在服务的工作目录中创建。

您可以将 "log.txt" 更改为完整路径或在 .service 文件中设置工作目录:

[Service]
WorkingDirectory=/path/you/want/the/file/to/be/in
…