2

This code is used to get stdout of the process

    NSTask       * task;
    NSPipe       * pipe;
    NSFileHandle * fileHandle;

    task       = [ [ NSTask alloc ] init ];
    pipe       = [ NSPipe pipe ];
    fileHandle = [ pipe fileHandleForReading ];

    [ task setLaunchPath: @"/usr/bin/lspci" ];
    [ task setArguments:[NSArray arrayWithObject:@"-nn"]];
    [ task setStandardOutput: pipe ];
    [ task setStandardError: pipe ];
    [ task launch ];
    [ task waitUntilExit]; 
    [ task release];

    NSData *outputData = [[pipe fileHandleForReading] readDataToEndOfFile];

    NSString *outputString = [[[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding] autorelease];

As /usr/bin/lspci does not exist on some systems, this fatal error occurs

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'launch path not accessible'

How to check beforehand that lspci does exist, and if it doesnt then display error message to user?

yolo
  • 2,757
  • 6
  • 36
  • 65

2 Answers2

5

To check if file exists and is executable:

BOOL exists = [[NSFileManager defaultManager] isExecutableFileAtPath:[task launchPath]];

Missing file is not the only reason why you can get an exception. You should always use @try-@catch block.

hamstergene
  • 24,039
  • 5
  • 57
  • 72
  • What can be the reason for this error?(assuming that the file exist and setlaunchpath succed) – Mike.R May 23 '13 at 08:45
  • 1
    @Mike.R One reason is that modern system have advanced file access control, so access denied error may happen to other reasons than not having Unix executable/readable bits set. Also, file systems are inherently race-prone: network connection can die, device can fail or be physically ejected, the file might have simply been deleted since you last checked its availability. – hamstergene May 23 '13 at 09:01
  • hamstegene I try to Launch Safari by replacing Safari executable with my own. So in my own executable i will start the authentic Safari app (for IOS simulator), I check all the path with try catch block and the place where i get this error is [task launch]. Do you have any idea how to investigate it? – Mike.R May 23 '13 at 09:17
  • @Mike.R You need to open new question for this. Comments are for improving the answer, not for general discussion. – hamstergene May 23 '13 at 13:58
  • Kind of agree with you, Thanks. – Mike.R May 23 '13 at 14:12
1
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:@"/usr/bin/lspci"];
if (!exists) {
   // handle error...
}
omz
  • 53,243
  • 5
  • 129
  • 141