Objective c “unix的目标C版本”;“手指”;命令

Objective c “unix的目标C版本”;“手指”;命令,objective-c,login,unix,Objective C,Login,Unix,我正在尝试检查自上次登录Cocoa应用程序以来的时间。我不想做这样的事情: NSTask *task; task = [[NSTask alloc] init]; [task setLaunchPath: @"/usr/bin/finger"]; NSArray *arguments; arguments = [NSArray arrayWithObject: NSUserName()]; [task setArguments: arguments]; NSPipe *pipe; pipe

我正在尝试检查自上次登录Cocoa应用程序以来的时间。我不想做这样的事情:

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/finger"];

NSArray *arguments;
arguments = [NSArray arrayWithObject: NSUserName()];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *stringData = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"%@", stringData);

例如,Unix
whoami
命令具有与目标C等效的
NSUserName
Objective C。

您可能必须从存储该信息的系统文件中读入该信息。可能是unix上的“utmp”文件


毕竟,“手指”就是这样做的。

这是一个非常有趣的问题!谢谢你的提问。:)

至于答案,我找到了来源,并得出以下结论:

#import <utmpx.h>

struct utmpx *user;
setutxent();
while ((user = getutxent()) != NULL) {
    if (user->ut_type == USER_PROCESS) {
        time_t loggedIn = user->ut_tv.tv_sec;
        NSDate * d = [NSDate dateWithTimeIntervalSince1970:loggedIn];
        NSLog(@"%s logged in at %@", user->ut_user, d);
    }
}
endutxent();
这与终端中的
finger dave
的输出相匹配:

Login: dave                     Name: Dave DeLong
Directory: /Users/dave                  Shell: /bin/bash
On since Mon Dec  6 09:59 (PST) on console, idle 7 days 9:18 (messages off)
On since Mon Dec 13 19:14 (PST) on ttys000
On since Thu Dec  9 17:21 (PST) on ttys001 (messages off)

这并不能真正解决您的问题,但我会注意到finger拥有世界上最简单的网络协议。Telnet至端口79,键入您的登录名,然后按return。所以你至少可以避免分叉。()
Login: dave                     Name: Dave DeLong
Directory: /Users/dave                  Shell: /bin/bash
On since Mon Dec  6 09:59 (PST) on console, idle 7 days 9:18 (messages off)
On since Mon Dec 13 19:14 (PST) on ttys000
On since Thu Dec  9 17:21 (PST) on ttys001 (messages off)