How to get something similar to Tail -f using NSTask

I need to read the last line added to the file magazine , in real time, and to fix the added row.

Something like Tail -f.

So, my first attempt was to use Tail -f using NSTask.

I do not see any output using the following code:

    NSTask *server = [[NSTask alloc] init];
    [server setLaunchPath:@"/usr/bin/tail"];
    [server setArguments:[NSArray arrayWithObjects:@"-f", @"/path/to/my/LogFile.txt",nil]];

    NSPipe *outputPipe = [NSPipe pipe];
    [server setStandardInput:[NSPipe pipe]];
    [server setStandardOutput:outputPipe];

    [server launch];
    [server waitUntilExit];
    [server release];

    NSData *outputData = [[outputPipe fileHandleForReading] readDataToEndOfFile];
    NSString *outputString = [[[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding] autorelease];
    NSLog (@"Output \n%@", outputString);

I see the result as expected when using:

[server setLaunchPath:@"/bin/ls"];
  • How can I capture the output of this NSTask tail?

  • Is there an alternative to this method where I can open a stream in a file and every time a line is added, display it on the screen? (basic logging functions)

+3
source share
2 answers

, readDataToEndOfFile , tail , tail -f (stdout). C I/O, FileTailer, . - , , . FileTailer.h, FileTailer.m .

. , ( ) ; EOF , ( refresh), .

- (void)readIndefinitely:(void (^)(int ch))action
{
    long pos = 0L;
    int ch = 0;

    while (1) {
        fseek(in, pos, SEEK_SET);
        int ch = fgetc(in);
        pos = ftell(in);
        if (ch != EOF) {
            action(ch);
        } else {
            [NSThread sleepForTimeInterval:refresh];
        }
    }
}

, :

FileTailer *tail = [[[FileTailer alloc] initWithStream:stdin refreshPeriod:3.0] autorelease];
[tail readIndefinitely:^ void (int ch) { printf("%c", ch); }];

(: FileTailer , , , , , à la tail -f.)

+4

"tail -f logfile" NSTask Objective-C:

asynctask.m - , , stdin, stdout stderr NSTask

...

(.. Foundation), asynctask.m NSRunLoop waitForDataInBackgroundAndNotify. , asynctask.m. pthread_create (3) pthread_detach (3) 64 stdin NSTask.

asynctask.m : http://www.cocoadev.com/index.pl?NSPipe

+1

Source: https://habr.com/ru/post/1784873/


All Articles