当前位置:   article > 正文

MacOS 开发 —后台启动程序_macos 执行脚本以后台

macos 执行脚本以后台

简介: 在实际的开发过程中,我们需要启动一些无窗口的应用程序。并且需要在后台启动程序,前台不需要做任何显示。这个时候,如果使用 NSTask 直接启动程序则前端则会启动终端。达不到我们想要的效果。这里可以通过脚本实现程序 后台启动(WandServer 为程序名称)。

启动脚本

startup.sh

#!/bin/bash

base_dir="$(dirname "$0")"
cd $base_dir

if [[ $# == 1 ]] && [[ $1 == "debug" ]];then
    nohup ./WandServer >debug.log 2>&1 &
else
    nohup ./WandServer >/dev/null 2>&1 &
fi

echo $! > ./WandServer.pid

echo "----"
echo "Wand Server started."

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
关闭脚本

shutdown.sh

#!/bin/bash

base_dir="$(dirname "$0")"
cd $base_dir

echo "----"
echo "Wand Server is shutting down..."

if [ -f ./WandServer.pid ];then
	pid=`cat ./WandServer.pid`
	kill $pid
	rm -f ./WandServer.pid

	echo ""
	echo "Done."
else
	echo ""
	echo "Error: pid file is NOT FOUND!"
fi

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
Xcode 实现
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *sourcePath = [[NSBundle mainBundle]resourcePath];
        
        NSString *serverPath = [sourcePath stringByAppendingString:@"/PrinterServer/"];
        NSString *startupPath = [serverPath stringByAppendingString:@"startup.sh"];
        NSString *shutdownPath = [serverPath stringByAppendingString:@"shutdown.sh"];
        NSLog(@"soource:%@  serverPath:%@ ",sourcePath,serverPath);
        NSTask * task = [NSTask new];
        [task setLaunchPath:startupPath];
      
        NSPipe *readPipe = [NSPipe pipe];
        
        NSFileHandle *readHandle = [readPipe fileHandleForReading];
        NSPipe *writePipe = [NSPipe  pipe];
        [task setStandardInput: writePipe];
        [task setStandardOutput: readPipe];
        [task launch];
        NSMutableData *data = [[NSMutableData alloc] init];
        NSData *readData;
        while ((readData = [readHandle availableData])&& [readData length])
        {
            [data appendData: readData];
        }
        
        NSString *strippedString;
        strippedString = [[NSString alloc]initWithData: data encoding:NSASCIIStringEncoding];
        NSLog(@"strippedString :\n\n %@",strippedString);
        
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/836092
推荐阅读
相关标签
  

闽ICP备14008679号