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."

关闭脚本

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

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);
        
    });

你可能感兴趣的:(Cocoa,macOS,开发)