MacOS 开发 —后台启动程序

本文介绍了一种在不显示任何窗口的情况下,通过脚本在后台启动应用程序的方法。使用nohup命令并重定向输出,确保程序运行时不干扰前端。同时,提供了启动和关闭脚本的示例,并展示了如何在Xcode中调用这些脚本来启动和停止WandServer程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介: 在实际的开发过程中,我们需要启动一些无窗口的应用程序。并且需要在后台启动程序,前台不需要做任何显示。这个时候,如果使用 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);
        
    });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值