创建一个 mac 的后台进程(daemon)

Mac中创建守护进程(Daemon)

创建一个可以执行的脚本 hello.sh
touch /Users/oslivan/test/hello.sh
chmod 755 /Users/oslivan/test/hello.sh
## hello.sh start
for((;;))
do
  echo "hello."
  sleep 3
done
## hello.sh end
创建一个 plist, 并通过 launchctl 加载
touch /Users/oslivan/Library/LaunchAgents/com.oslivan.test.hello.plist
## com.oslivan.test.hello.plist start
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.oslivan.test.hello</string>
        <key>ProgramArguments</key>
        <array>
            <string>/Users/oslivan/test/hello.sh</string>
        </array>
        <key>StandardOutPath</key>
        <string>/Users/oslivan/test/logfile.log</string>
        <key>StandardErrorPath</key>
        <string>/Users/oslivan/test/logfile_error.log</string>
        <key>RunAtLoad</key>
        <true/>
        <key>KeepAlive</key>
        <true/>
    </dict>
</plist>
## com.oslivan.test.hello.plist end
launchctl load /Users/oslivan/Library/LaunchAgents/com.oslivan.test.hello.plist
测试是否启动成功
ps -ef | grep hello
cd /Users/oslivan/test/ && tail logfile.log
参考

Sample Guide
launchd.plist 语法
launchd 教程

转载于:https://www.cnblogs.com/zhangyanpei/p/7136409.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一个简单的守护进程可以通过以下步骤实现: 1. 使用 `fork()` 函数创建进程,然后让父进程退出,使子进程成为孤儿进程,从而与终端断开关联。 2. 使用 `setsid()` 函数创建新的会话,使子进程成为新的会话组长和进程组长,也就是守护进程。 3. 使用 `chdir()` 函数将当前工作目录切换到根目录 `/`,以避免影响到其他目录和文件。 4. 使用 `umask()` 函数设置文件创建时的权限掩码,以避免出现安全问题。 5. 使用 `close()` 函数关闭标准输入、标准输出和标准错误流,以避免输出到终端或其他地方。 6. 在一个无限循环中,使用 `sleep()` 函数等待 60 秒,然后输出字符串 `hilo`。 具体实现方法如下: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> int main() { pid_t pid; pid = fork(); if (pid == -1) { perror("fork"); exit(1); } else if (pid > 0) { // 父进程退出 exit(0); } // 子进程 setsid(); // 创建新会话 chdir("/"); // 切换工作目录 umask(0); // 设置文件创建时的权限掩码 close(STDIN_FILENO); // 关闭标准输入 close(STDOUT_FILENO); // 关闭标准输出 close(STDERR_FILENO); // 关闭标准错误 while (1) { sleep(60); // 等待 60 秒 printf("hilo\n"); // 输出 hilo fflush(stdout); // 刷新输出缓冲区 } return 0; } ``` 首先,使用 `fork()` 函数创建进程。如果 `fork()` 函数返回值为 `-1`,则说明创建进程失败,此时使用 `perror()` 函数输出错误信息,并退出程序。如果 `fork()` 函数返回值大于 `0`,则说明当前进程是父进程,此时退出程序。如果 `fork()` 函数返回值为 `0`,则说明当前进程是子进程,此时调用 `setsid()` 函数创建新的会话,并将当前进程设置为新的会话组长和进程组长。然后,使用 `chdir()` 函数将当前工作目录切换到根目录 `/`,使用 `umask()` 函数设置文件创建时的权限掩码为 0。接着,使用 `close()` 函数关闭标准输入、标准输出和标准错误流。最后,在一个无限循环中,使用 `sleep()` 函数等待 60 秒,然后输出字符串 `hilo`,并使用 `fflush()` 函数刷新输出缓冲区,以确保输出立即被打印到文件或终端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值