赞
踩
简介: 在实际的开发过程中,我们需要启动一些无窗口的应用程序。并且需要在后台启动程序,前台不需要做任何显示。这个时候,如果使用 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
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);
});
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。