0

I am trying to schedule a shutdown event with pmset executed via NSTask in OSX app.

 NSCalendar *cal = [NSCalendar new];
NSDate *dateNext = [date dateByAddingTimeInterval:120];

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM/dd/YYYY HH:mm:ss"];
NSString* dS = [df stringFromDate:dateNext];

//# pmset schedule shutdown "MM/DD/YYYY HH:MM:SS"

NSString* dateString = [NSString stringWithFormat:@"\"%@\"", dS];
NSLog(@"Date to set %@", dateString);

int pid = [[NSProcessInfo processInfo] processIdentifier];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/pmset";
NSArray *args = [NSArray arrayWithObjects:@"schedule",@"shutdown", dateString, nil];

[task setArguments:args];
task.standardOutput = pipe;
[task launch];

NSData *data = [file readDataToEndOfFile];
[file closeFile];

NSString *out = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"Result:\n%@", out);

The log shows as follows:

2019-09-12 12:38:53.470793+0100 TheApp[51008:4925389] Date to set "09/12/2019 12:40:53"
2019-09-12 12:38:53.518372+0100 TheApp[51008:4925389] Result:
Error: Badly formatted date (2)
Error parsing scheduled event.

The dateString argument seems to be correctly formatted between quotes, as required by pmset, but I keep getting such error. Is there some parameter missing in NSTask?

Thank you.

MobileCushion
  • 7,065
  • 7
  • 42
  • 62
  • Thanks for the comment. Using that date format results in the same error. I am using the date format as seen in the code on ther terminal and it runs ok. So I'm guessing there is some issue with NSTask parsing the arguments... – MobileCushion Sep 12 '19 at 12:35
  • Take the quotes off the date time. I know `man pmset` says they're needed, maybe that's only if your calling it through the shell? :shrug: – TheNextman Sep 12 '19 at 23:11
  • @TheNextman is right, but no need to :shrug: - the shell breaks up command arguments using spaces, the quotes tell the shell to pass the date as one argument. When passing the arguments programmatically you can include spaces and don't need, and must not include, the shell's quotes. – CRD Sep 13 '19 at 01:39
  • And from the [documentation](https://developer.apple.com/documentation/foundation/nstask/1408983-arguments?language=objc): "NSTask object converts both path and the strings in arguments to appropriate C-style strings [...] strings in arguments do not undergo shell expansion, so you do not need to do special quoting". @CRD is right; `man pmset` says the quotes are needed, but it's clearly talking about being invoked from the shell. – TheNextman Sep 13 '19 at 02:49

0 Answers0