2
votes

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?

2

2 Answers

5
votes

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.

1
votes
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:@"/usr/bin/lspci"];
if (!exists) {
   // handle error...
}