Week 9 - Monday CS222.

Slides:



Advertisements
Similar presentations
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Advertisements

System Files and Process Environment Password file Group file System identification Time Process environment.
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Week 8 - Friday.  What did we talk about last time?  String to int conversions  Users and groups  Password files.
Adding New Users User as an entity - username(UID), GID. UID - typically a number for system to identify the user. GID – a number that recognizes a set.
IT2204: Systems Administration I 1 6b). Introduction to Linux.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1 post-mortem  Recursive running time.
ITI-481: Unix Administration Meeting 3 Christopher Uriarte, Instructor Rutgers University Center for Applied Computing Technologies.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1!  And before that…  Review!  And before that…  Arrays and strings.
Users Greg Porter V1.0, 26 Jan 09. What is a user? Users “own” files and directories Permission based on “ownership” Every user has a User ID (UID) 
Learners Support Publications Classes and Objects.
Week 9 - Monday.  What did we talk about last time?  Time  GDB.
Managing Users  Each system has two kinds of users:  Superuser (root)  Regular user  Each user has his own username, password, and permissions that.
Chapter 3 & 6 Root Status and users File Ownership Every file has a owner and group –These give read,write, and execute priv’s to the owner, group, and.
Interacting with Unix. Getting the Process ID u Synopsis #include pid_t getpid(void); u Example: #include int main(){ pid_t n = getpid(); printf("Process.
The Saigon CTT Chapter 10 Managing Users. The Saigon CTT  Objectives  Define the requirements for user accounts  Explain group and group accounts 
CSC414 “Introduction to UNIX/ Linux” Lecture 6. Schedule 1. Introduction to Unix/ Linux 2. Kernel Structure and Device Drivers. 3. System and Storage.
Week 9 - Wednesday.  What did we talk about last time?  structs.
Week 15 - Wednesday.  What did we talk about last time?  Review up to Exam 1.
Advanced Programming in the UNIX Environment Hop Lee.
EGR 2261 Unit 13 Classes Read Malik, Chapter 10.
Last week: We talked about: History of C Compiler for C programming
Chapter VII: Arrays.
Week 8 - Wednesday CS222.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo
LINKED LISTS.
Lesson #8 Structures Linked Lists Command Line Arguments.
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Week 4 - Friday CS222.
User-Written Functions
The Machine Model Memory
Module X (Unix/Linux Password Security)
11 Chapter Structured Data
A bit of C programming Lecture 3 Uli Raich.
Week 3 - Friday CS222.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Week 9 - Wednesday CS222.
UNIX System Overview.
COSC 220 Computer Science II
Other Kinds of Arrays Chapter 11
Getting Started with C.
Chapter 2 User Management
Week 4 - Monday CS222.
Programmazione I a.a. 2017/2018.
Arrays in C.
Adding New Users, Storage, File System
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
C Structures, Unions, Bit Manipulations and Enumerations
OOP Paradigms There are four main aspects of Object-Orientated Programming Inheritance Polymorphism Abstraction Encapsulation We’ve seen Encapsulation.
Number and String Operations
Classes and Objects.
Pointers.
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Java Programming Language
Data Structures & Algorithms
Homework Finishing Chapter 2 of K&R. We will go through Chapter 3 very quickly. Not a lot is new. Questions?
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Rootly Powers Chapter 3.
Standard Version of Starting Out with C++, 4th Edition
Adding New Users.
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Classes and Objects Object Creation
Week 6 - Monday CS221.
Week 2 - Friday CS222.
Week 9 - Monday CS222.
Presentation transcript:

Week 9 - Monday CS222

Last time What did we talk about last time? Testing GDB Lab 8

Questions?

Project 4

Quotes On two occasions I have been asked: "Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?" I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question. Charles Babbage

Some String Issues

A few final string issues What if you have a number and want a string version of it? In Java: What if you have a string that gives a numerical representation and you want the number it represents? int x = 3047; String value = "" + x; //quick way value = Integer.toString(x); //fussy way String value = "3047"; int x = Integer.parseInt(value);

String to integer In C, the standard way to convert a string to an int is the atoi() function #include <stdlib.h> to use it #include <stdlib.h> #include <stdio.h> int main() { char* value = "3047"; int x = atoi(value); printf("%d\n", x); return 0; }

Implementing atoi() Now it's our turn to implement atoi() Signature: int atoi(char* number);

Integer to string Oddly enough, this is a stranger situation Many systems have a non-standard function (also in stdlib.h) called itoa() It takes the int, a buffer to hold the resulting string, and the base The portable way to do this is to use sprintf() It's like printf() except that it prints things to a string buffer instead of the screen char value[10]; //has to be big enough int x = 3047; itoa( x, value, 10 ); char value[10]; //has to be big enough int x = 3047; sprintf( value, "%d", x );

Implementing itoa() Now it's our turn to implement itoa() We'll restrict ourselves to a base 10 version Signature: It returns the pointer to the string in case this call is nested inside of another call (to strcat() or printf() or whatever) char* itoa(int number, char* string);

Structs

Structs A struct in C is: They were called records in Pascal A collection of one or more variables Possibly of different types Grouped together for convenient handling. They were called records in Pascal They have similarities to classes in Java Except all fields are public and there are no methods Struct declarations are usually global They are outside of main() and often in header files

struct name { type1 member1; type2 member2; type3 member3; ... }; Anatomy of a struct struct name { type1 member1; type2 member2; type3 member3; ... };

Why should we bother? Some data is naturally grouped together For example, a roster of students where each student has a name, GPA, ID number You could keep an array of strings, double values, and int values that corresponded to each other But then sorting by GPA would mean moving values in three different arrays Also, we'll need structs for linked lists and trees

Java examples In Java, a struct-like class would be used to group some data conveniently Examples: A class to hold a point in space A class to hold student data public class Point { private double x; private double y; //constructor //methods } public class Student { private String name; private double GPA; private int ID; //constructor //methods }

C examples The C equivalents are similar Just remember to put a semicolon after the struct declaration A string can either be a char* (the memory for it is allocated elsewhere) or a char array with a maximum size Examples: A struct to hold a point in space A struct to hold student data struct point { double x; double y; }; struct student { char name[100]; double GPA; int ID; };

Declaring a struct variable Type: struct The name of the struct The name of the identifier You have to put struct first! struct student bob; struct student jameel; struct point start; struct point end;

Accessing members of a struct Once you have a struct variable, you can access its members with dot notation (variable.member) Members can be read and written struct student bob; strcpy(bob.name, "Bob Blobberwob"); bob.GPA = 3.7; bob.ID = 100008; printf("Bob's GPA: %f\n", bob.GPA);

Initializing structs There are no constructors for structs in C You can initialize each element manually: Or you can use braces to initialize the entire struct at once: struct student julio; strcpy(julio.name, "Julio Iglesias"); julio.GPA = 3.9; julio.ID = 100009; struct student julio = { "Julio Iglesias", 3.9, 100009 };

Assigning structs It is possible to assign one struct to another Doing so is equivalent to using memcpy() to copy the memory of julio into the memory of bob bob is still separate memory: it's not like copying references in Java struct student julio; struct student bob; strcpy(julio.name, "Julio Iglesias"); julio.GPA = 3.9; julio.ID = 100009; bob = julio;

Putting arrays and pointers in structs It is perfectly legal to put arrays of values, pointers, and even other struct variables inside of a struct declaration If it's a pointer, you will have to point it to valid memory yourself struct point { double x; double y; }; struct triangle struct point vertices[3];

Dangers with pointers in structs With a pointer in a struct, copying the struct will copy the pointer but will not make a copy of the contents Changing one struct could change another struct person { char* firstName; char* lastName; }; struct person bob1; struct person bob2; bob1.firstName = strdup("Bob"); bob1.lastName = strdup("Newhart"); bob2 = bob1; strcpy(bob2.lastName, "Hope"); printf("Name: %s %s\n", bob1.firstName, bob1.lastName); //prints Bob Hope

Using arrays of structs An array of structs is common Student roster List of points Like any other array, you put the name of the type (struct name) before the variable, followed by brackets with a fixed size An array of structs is filled with uninitialized structs whose members are garbage struct student students[100];

Pointers to structs Similarly, we can define a pointer to a struct variable We can point it at an existing struct We can dynamically allocate a struct to point it at This is how linked lists are going to work struct student bob; struct student* studentPointer; strcpy(bob.name, "Bob Blobberwob"); bob.GPA = 3.7; bob.ID = 100008; studentPointer = &bob; (*studentPointer).GPA = 2.8; studentPointer = (struct student*) malloc(sizeof(struct student));

Arrow notation As we saw on the previous page, we have to dereference a struct pointer and then use the dot to access a member This is cumbersome and requires parentheses Because this is a frequent operation, dereference + dot can be written as an arrow (->) struct student* studentPointer = (struct student*) malloc(sizeof(struct student)); (*studentPointer).ID = 3030; studentPointer->ID = 3030;

Passing structs to functions If you pass a struct directly to a function, you are passing it by value A copy of its contents is made It is common to pass a struct by pointer to avoid copying and so that its members can be changed void flip(struct point* value) { double temp = value->x; value->x = value->y; value->y = temp; }

Gotchas Always put a semicolon at the end of a struct declaration Don't put constructors or methods inside of a struct C doesn't have them Assigning one struct to another copies the memory of one into the other Pointers to struct variables are usually passed into functions Both for efficiency and so that you can change the data inside

Example Write a function that takes two point structs and returns the distance between them struct point { double x; double y; };

Example Read in 100 student names, GPAs, and ID numbers Sort them by ID numbers Print out the values struct student { char name[100]; double GPA; int ID; };

Users and Groups

Users Recall that each user on a Linux system has a unique login name and a unique numerical identifier (the UID) Users can belong to one or more groups as well Where is this information stored?

Password file The system has a password file stored in /etc/passwd Each line of this file corresponds to one user in the system and has seven fields separated by colons: Login name Encrypted password UID GID (group ID of the first group that the user is a member of) Comment Home directory (where you are when you log in) Login shell (which shell you running when you log in) Example: wittmanb:x:1000:100:Barry Wittman:/home/wittmanb:/bin/bash

Catch-22 Your computer needs to be able read the password file to check passwords But, even root shouldn’t be able to read everyone’s passwords Hash functions to the rescue!

Cryptographic hash functions Take a long message and turn it into a short digest Different from hash functions used for hash tables Lots of interesting properties (lots more than these): A small change in the message should make a big change in the digest Avalanching Given a digest, should be hard to find a message that would produce it Preimage Resistance Should be hard to find two messages that hash to the same digest (collision) Collision Resistance

The Linux and Unix solution Instead of storing actual passwords, Linux machines store the hash of the passwords When someone logs on, the operating system hashes the password and compares it to the stored version No one gets to see your original password Not even root!

Back to the password file Inside the password file, we have encrypted passwords Everyone's password is safe after all Login Name Password Hash ahmad IfW{6Soo baili 853aE90f carmen D390&063 deepak CWc^Q3Ge erica e[6s_N*X1

Shadow password file Even though the password is disguised, it is unwise to let it be visible to everyone Given a password digest (the hashed version) and lots of time, it is possible to figure out the password It's useful for the password file to be readable by everyone so that all users on a machine are known to all others A shadow password file stores the encrypted password and is readable only by privileged users /etc/shadow

Changing your password Amid all this discussion, it might be useful to know how to change your password I don't recommend that you do change your password I'm honestly not sure how doing so will interact with your Active Directory (Windows) password The command is passwd Changing password for wittmanb. (current) UNIX password: Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully

Changing the owner of a file You recall that we can change permissions for who can read, write, and execute a file using chmod But chmod depends on who the owner is What if you want someone else to be the owner of a file? The chown command can let you do that If I want my file stuff.txt to be owned by Dr. Leap, I would use the following command On most systems, chown only works if you are root chown leap stuff.txt

Groups Files are associated with a group as well as a user who is owner The groups are listed in the /etc/group file Each line of this file corresponds to a group and has four fields separated by colons: Group name Encrypted password Often not used Group ID (GID) User list Comma separated Example: users:x:100: jambit:x:106:claus,felli,frank,harti,markus,martin,mtk,paul

Creating a group If you want to create a group, you have to be root If you're root (or using sudo), you can use the groupadd command To create the awesome group as root: Or using sudo: groupadd awesome sudo groupadd awesome

Adding a user to a group Again, you have to be root to add a user to a group Use the useradd command To add user wittmanb to the awesome group as root: Or using sudo: useradd –g awesome wittmanb sudo useradd –g awesome wittmanb

Changing the group for a file When you create a file, it is associated with some default group that you belong to You can use the chgrp command to change to another group that you belong to If you are root, you can use the chown command to change the group, using a colon chgrp awesome file.txt chown :awesome file.txt

Time

Time In the systems programming world, there are two different kinds of time that are useful Real time This is also known as wall-clock time or calendar time It's the human notion of time that we're familiar with Process time Process time is the amount of time your process has spent on the CPU There is often no obvious correlation between process time and real time (except that process time is never more than real time elapsed)

Calendar time For many programs it is useful to know what time it is relative to some meaningful starting point Internally, real world system time is stored as the number of seconds since midnight January 1, 1970 Also known as the Unix Epoch Possible values for a 32-bit value range from December 13, 1901 to January 19, 2038 Systems and programs that use a 32-bit signed int to store this value may have strange behavior in 2038

time() The time() function gives back the seconds since the Unix Epoch Its signature is: time_t is a signed 32-bit or 64-bit integer You can pass in a pointer to a time_t variable or save the return value (both have the same result) Typically we pass in NULL and save the return value Include time.h to use time() time_t time(time_t* timePointer); time_t seconds = time(NULL); printf("%d seconds have passed since 1970", seconds);

Time structures Many time functions need different structs that can hold things One such struct is defined as follows: struct timeval { time_t tv_sec; // Seconds since Epoch suseconds_t tv_usec; // Extra microseconds };

gettimeofday() The gettimeofday() function offers a way to get higher precision timing data Its signature is: From the previous slide, timeval has a tv_secs member which is the same as the return value from time() It also has a tv_usec member which gives microseconds (millionths of a second) The timezone pointer tz is obsolete and should have NULL passed into it Include sys/time.h (not the same as time.h) to use this function int gettimeofday(struct timeval *tv, struct timezone *tz);

Timing with gettimeofday() gettimeofday() is a reliable way to see how long something takes Get the start time, the end time, and subtract them double start; double end; struct timeval tv; gettimeofday(&tv, NULL); start = tv.tv_sec + tv.tv_usec/1000000.0; someLongRunningFunction(); end = tv.tv_sec + tv.tv_usec/1000000.0; printf("Your function took %.3f seconds", end – start);

ctime() What about printing out a human-readable version of the time? ctime() takes a time_t value and returns a string giving the day and time Alternatively, strftime() has a set of specifiers (similar to printf()) that allow for complex ways to format the date and time printf(ctime(time(NULL)); //prints Fri Mar 15 14:22:34 2013

Broken down time structure struct tm { int tm_sec; // Seconds (0-60) int tm_min; // Minutes (0-59) int tm_hour; // Hours (0-23) int tm_mday; // Day of the month (1-31) int tm_mon; // Month (0-11) int tm_year; // Year since 1900 int tm_wday; // Day of the week (Sunday = 0) int tm_yday; // Day in the year (0-365; 1 Jan = 0) int tm_isdst; /* Daylight saving time flag > 0: DST is in effect; = 0: DST is not effect; < 0: DST information not available */ };

gmtime(), localtime(), and mktime() gmtime() and localtime() convert a time_t value to a struct that contains "broken down" time gmtime() gives UTC time (used to be called Greenwich Mean Time) localtime() gives the local time, assuming it is set up correctly mktime() can convert from a broken down time back into time_t time_t seconds = time(NULL); struct tm* brokenDownTime = NULL; brokenDownTime = localtime(&seconds); if( (*brokenDownTime).tm_wday == 1 ) printf("It's just another manic Monday.\n");

Jiffies How accurate is the microsecond part of gettimeofday()? It depends on the accuracy of the software clock in your system This clock measures time in units called jiffies A jiffy used to be 10 milliseconds (100 Hz) They raised the accuracy to 1 millisecond (1000 Hz) Now, it can be configured for your system to 10, 4 (the default), 3.3333, and 1 milliseconds

Process time For optimization purposes, it can be useful to know how much time a process spends running on the CPU This time is often broken down into User time: the amount of time your program spends executing its own code System time: the amount of time spent in kernel mode executing code for your program (memory allocation, page faults, file opening)

The time command You can time a program's complete execution by running it with the time command It will give the real time taken, user time, and system time Let's say you've got a program called timewaster Run it like this: Output might be: time ./timewaster real 0m4.84s user 0m1.030s sys 0m3.43s

Quiz

Upcoming

Next time… More practice with structs Linked lists typedef

Reminders Keep working on Project 4 Keep reading K&R chapter 6 Due Friday Keep reading K&R chapter 6 Looking for an internship or full-time job? Bring your resume to the Masters Center Mineral Gallery this Wednesday, March 22 from 11am – 1pm