创建daemon进程适用于android/linux/mac

# 跨平台通用daemon

```

static int fds[2];

    int flag;

    pipe(fds);

    flag = fcntl(fds[0], F_GETFL, 0);

    fcntl(fds[0], F_SETFL, flag | O_NONBLOCK);

    flag = fcntl(fds[1], F_GETFL, 0);

    fcntl(fds[1], F_SETFL, flag | O_NONBLOCK);

    int forkpid = fork();

    if (forkpid < 0) {

        return -1;

    } else if (forkpid > 0) { // father

        sleep(1);

        return 0;

    }

    setsid();

    chdir("/");

    umask(0);

    int null_in = open("/dev/null", O_RDONLY);

    int null_out = open("/dev/null", O_WRONLY);

    dup2(null_in, STDIN_FILENO);

    dup2(null_out, STDOUT_FILENO);

    dup2(null_out, STDERR_FILENO);

    for(unsigned int i = 0; i < 1024; i++) {

        close(i);

    }

```


### theos makefile命令

```

before-install::  

    install.exec "echo before-install"

before-uninstall::

    install.exec "echo before-uninstall"

after-install::

    install.exec "echo after-install"

after-uninstall::

    install.exec "echo after-uninstall"


子命令:

install.exec 执行命令

install.copyFile 拷贝文件


注意以上逻辑不会打包到deb文件中,下面来看一种可以打包到deb的方法

```

### deb控制命令


Theos工程下的Layout目录会被打包到deb中

而控制命令包含如下:

preinst

在Deb包文件解包之前,将会运行该脚本。许多“preinst”脚本的任务是停止作用于待升级软件包的服务,直到软件包安装或升级完成。

postinst

该脚本的主要任务是完成安装包时的配置工作。许多“postinst”脚本负责执行有关命令为新安装或升级的软件重启服务。

prerm

该脚本负责停止与软件包相关联的daemon服务。它在删除软件包关联文件之前执行。

postrm

该脚本负责修改软件包链接或文件关联,或删除由它创建的文件。

extrainst_

安装是执行,升级时不执行


在这5个脚本中,传入的参数为install upgrade remove purge

## iOS 创建系统daemon进程

参考:https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html

1.配置源文件

a./layout/tmp/test.sh内容

echo $2 >> /tmp/testlog >> /tmp/testlog

sleep 5

b./Library/LaunchDaemons/test.plist内容

    KeepAlive

   

    Label

    test

    ProgramArguments

   

        /bin/bash

        /tmp/test.sh

   

    RunAtLoad

   

c./layout/DEBIAN/prerm内容

#!/bin/sh

if [[ $1 == remove || $1 == purge ]]; then

    if [ -f "/Library/LaunchDaemons/test.plist" ]; then

      /bin/launchctl unload /Library/LaunchDaemons/test.plist

    fi

fi

exit 0

d./layout/DEBIAN/extrainst_内容

#!/bin/sh

if [[ $1 == upgrade ]]; then

    if [ -f "/Library/LaunchDaemons/test.plist" ]; then

      if [ ! -d "/usr/lib/TweakInject" ]; then

        /bin/launchctl unload /Library/LaunchDaemons/test.plist

        /bin/launchctl load /Library/LaunchDaemons/test.plist

      else

        /bin/launchctl kickstart -k system/test

        /bin/launchctl load /Library/LaunchDaemons/test.plist

      fi

    fi

elif [[ $1 == install ]]; then

    if [ -f "/Library/LaunchDaemons/test.plist" ]; then

      /bin/launchctl load /Library/LaunchDaemons/test.plist

    fi

fi

exit 0

注意control也放到/layout/DEBIAN中

你可能感兴趣的:(创建daemon进程适用于android/linux/mac)