Objective-c - User's login and logout time

后端 未结 1 2083
执念已碎
执念已碎 2021-01-12 15:09

is it possible to get user\'s login and logout time in a objective-c program? I can get the session ID, username, userUID, userIsActive and loginCompleted with CGSessionCopy

1条回答
  •  青春惊慌失措
    2021-01-12 15:33

    I don't know if there are any special Cocoa function to get user login/logout time.

    But you can read the login/logout history directly, using getutxent_wtmp(). This is what the "last" command line tool does, as can be seen in the source code: http://www.opensource.apple.com/source/adv_cmds/adv_cmds-149/last/last.c

    Just to give a very simple example: The following program prints all login/logout times to the standard output:

    #include 
    #include 
    
    int main(int argc, const char * argv[])
    {
        struct utmpx *bp;
        char *ct;
    
        setutxent_wtmp(0); // 0 = reverse chronological order
        while ((bp = getutxent_wtmp()) != NULL) {
            switch (bp->ut_type) {
                case USER_PROCESS:
                    ct = ctime(&bp->ut_tv.tv_sec);
                    printf("%s login %s", bp->ut_user, ct);
                    break;
                case DEAD_PROCESS:
                    ct = ctime(&bp->ut_tv.tv_sec);
                    printf("%s logout %s", bp->ut_user, ct);
                    break;
    
                default:
                    break;
            }
        };
        endutxent_wtmp();
    
        return 0;
    }
    

    And just for fun: A Swift 4 solution:

    import Foundation
    
    extension utmpx {
        var userName: String {
            return withUnsafePointer(to: ut_user) {
                $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: ut_user)) {
                    String(cString: $0)
                }
            }
        }
        var timestamp: Date {
            return Date(timeIntervalSince1970: TimeInterval(ut_tv.tv_sec))
        }
    }
    
    setutxent_wtmp(0)
    while let bp = getutxent_wtmp() {
    
        switch bp.pointee.ut_type {
        case Int16(USER_PROCESS):
            print(bp.pointee.userName, "login", bp.pointee.timestamp)
        case Int16(DEAD_PROCESS):
            print(bp.pointee.userName, "logout", bp.pointee.timestamp)
        default:
            break
        }
    }
    endutxent_wtmp();
    

    0 讨论(0)
提交回复
热议问题