Thursday, February 21, 2008

CSE2031 lecture 12

SystemCalls

  • Check out these books
    • Stevens Advanced Programming in the unix Environment
    • Robins&Robins – unix systems programming

  • Processes
    • Fork
    • Exec….


     

  • Files
    • Open
    • Close
    • Read
    • Write
    • Lseek
    • Dup
    • Dup2


 

PerProcess file Descriptor table

System wide open file table

I-Nodes

File descriptors

Flags

Disk / device

0

Offset

 

1

To i-node

 

2

  

..

  
  • Write(fd,buf,50)
    • Fd
      • File descriptor
    • Buf
      • Void* char
    • 50
      • #bytes
  • Write(fd,"Hello",6)
    • If this was typed after the first line there would be an offset of 56
  • Lseek
    • Lseek(fd,offset,WHENCE)
      • Fd
        • File descriptor
      • Offset
      • WHENCE
        • SEEK_SET
        • SEEK_CUR
        • SEEK_END
  • Dup
    • Duplicates a file descriptor using another file descriptor
      • Int dup(int oldfd);
      • Int dup2(int oldfd, int newfd)
    • Why would you want to do that?
      • Because you would never want to do this
        • Dup2(fd,1);
          • First argument is one you want copied
          • Second is what you want it copied on
        • Close(fd);
        • Printf("hello\n";
        • This would write at a file temp

int a[15]


 


 

int (*a)[15] /** a is a pointer to an array of 15 ints**/


 

int fd

fd = open("temp", _|_|_, 0660)

/*for the last input '0660' there should always be a leading 0 because it is an octal*/

/*_| represents space for flags*/


 

#define    O_WRONLY    1<<4

    O_TRUNK    1<<2

---------------------------------------

fd = open("temp", ..flag..)

write(fd,...)

close(fd)x

---------------------------------------


 

always check the return value from a system acall


 

if((fd = open("temp", ..flags..))<0){perror("...."); exit(1)}


 

for every file there exists an 'I-Node"

along with an I-Node there is a system-wide openfiletable

and with that there is a perprocess file descriptor table

Tuesday, February 19, 2008

CSE2031 Lecture 11

    #include<stdio.h>


 

int main(int argc, char* argv[])

{


 

return 0;

]


 

-------------------------------------------------------------

command line arguments

-------------------------------------------------------------

args can be accessed just like a normal allocated array

printf("%s\n", argx[2]);


 

-------------------------------------------------------------

bit operations

-------------------------------------------------------------


 

used to be used to pack and unpack things into small space, but space is cheap now.


 

operating on bits


 

logical operators (unary) bitwise complement ~

    bitwise AND    &

    bitwise XOR    `

    bitwise OR    |


 

shift operators

    left shift        <<

    right shift        >>


 

do not confuse & with &&

     or | with ||


 

right shift shifts in ?? on left end

for unsigned, zeros shifted on the left end

for signed, machine dependent

    -shift in zeros

    -shit in sign bits

int    a=1 << 31; /* shift 1 to high bit*/

unsinged    b = 1 << 31;


 

expn        representation

a        10000000 00000000 00000000 00000000

a >> 3        11110000 00000000 00000000 00000000

b        10000000 00000000 00000000 00000000

b >> 3        00010000 00000000 00000000 00000000


 

to turn bits on , use OR and 1's

v | 3 << 2

v | 00000000 00001100

has 3rd and 4th bit on, others as in v


 

to turn bits off, use AND and 0's

    v & ~(3<<2)

    v & 11111111 11110011

    has 3rd and 4th bit off, others as in v


 

masks


 

    -a string of bits used to extract bits from another expression

    -to find value of a particular bit in an expression

    - use a mask that is 1 at that bit and 0


 

otherwise


 

    1 << 2 as mask to query 3rd bit in v

    (v & (1 << 2) ) ? 1 : 0


 

    has value 1 if 3rd bit in v is 1 and 0 otherwise


 

bit representation of 255

    00000000 00000000 00000000 11111111

    

    0    --> all 0's

    ~0     --> all 1's

    ~0<<k     --> 111...11 000..0

~0(~0<<k)<<r     --> 000..0 11111111 000.00


 

Thursday, February 7, 2008

CSE2031 Lecture 10

Specifier

Field type

Converted using

Arg is pointer to

d

Integer (optionally signed)

Strtol with base 10

Int

hd

''

''

Short int

ld

''

''

Long int

I

''

Strtol with base = 0

Reads 045 as octal

Ox92 as hexadecimal

 

hi

  

Short

li

''

''

Long

O

Integer

Strtoul base 8

Unsigned int

ho

''

''

Unsigned short

Lo

''

''

Unsigned long

U

''

Base 10

''

Hu

''

''

''

Lu

''

''

''

X

Integer

Strtoul base 16

Does not accept AB

Unsigned int

Hx

''

''

''

Lx

''

''

''

E

Floating point input field

Strtol

Float

le

''

''

Double

Le

''

''

Long double

    


 


 

fscanf

-----------------------------------------

#include <stdio.h>

int fscanf(FILE*stream, const char * format, ...)

scanf is like fscanf(stdin,...)

sscanf(const char* src, ...format...

return value = # of text fields converted to values that are stored

scanf("%d %f", &n,&x)

return EOF if the function stops scanning

because the attempt to get next character it sets end of file or error indicator

for stream ferror(fp), feof(fp)

--------------------------------------------

format string

---------------------------------------------

can have white space

matches any amount of whitespace in the input

"%d<>%f

<> represents a space

literal text

scan conversion specifier

    -like those from printf ( sort of )

-------------------------------------------------

conversion specifier

---------------------------------------------------

-start w/ % sign

-*assignment supression

    looks like scanf(%d %*d %d &m)

-w field width

-conversion specifier

    -give type of argument to expect

        -always a pointer to something

    -how to determind conversion field

    -how to convert value to store

    

(a) scan set

[ ]

keep reading any of these characters (above)

{^ }

Don't read these characters (above)

b) otherwise (and usually)

    d

    i

    o    hl

    u

    x

    X

d and i are different in scan f


 

    eE

    fF    lL

    gG


 

    c

    s

    n

    p


 

-------------------------------

%wc    w chars no '\0' appended        store arg char*

defaults to 1 for %c


 

%ws    w chars                charx then append '\0'

default %s all of next token


 

scanf("%10c", buf)             reads first 10 chars even if it is whitespace

scanf("%10s", buf)            skips all the whitespace reads first 10 chars


 

char *p;

strtol(" 347atx ", &p, 6);

//skips whitespace and reads legal digits in 'this' base (this being 6)

//returns 22 (3 sixes + 4) and pointer p points to the 7

if value outside the range it will return LONG_MAX/ LONG_MIN + set errno to ERANGE

0 <-- system call

-1

x

---------------------------

file* <--Fopen

NULL

x

------------------------------

perror("usermessage");            prints out "usermessage: system error messsage" error message corresponding to error number

strerror(errno)                 returns appropriate error string


 


 


 

            

Tuesday, February 5, 2008

CSE 2031 Lecture 9

Assignment FAQ

Output files as they are read. For first question : instead of outputting palendromes output 'line is too long' after a certain length.

file* ß fopen(…)

file* fp;

fp = fopen("temp","a");

fprintf(fp,'%s\n", "Hello");

.

.

.

fclose(fp);

printf == fprintf(stdout,…);

"r+" opens a file for reading and writing

"w+" creates a file or truncates it if it exists and reads and writes to it

File descriptor talks to offset talks to inode

When you give a command like write you specify a file descriptor, where you find the data and how much you want to write

A file is a sequence of bytes,

Fseek, frewind, fsetpos are ways to specify the file pointer and where in the file you would like to go in the offset

States of a stream

  • Opened
    • If you write you go to ..
      • Writing state
        • If you continue writing you stay in the write state
        • If you use seek or rewind you will go back to
          • Opened state
        • If you just finished writing then you read
          • Error state
    • If you read you go to
      • Reading state
        • If you continue reading you stay in the read state
        • I f you just finished reading then you write
          • Error state


 

Printf(format string; other args)

Format string

  • Literal text
  • Conversion specifier
    • Printf("hello world \n");
    • ^literal text
  • Printf("n=%d\n", n);
    • Literal text
      • "n=" + "\n"
    • Conversion specifier
      • "%d"
    • Other arguments
      • "n"
  • Using print f
    • A char and short is always converted to int
    • A float is always converted to double

Conversion specifier

  • Starts with "%"
    • 4 components (in order)
      • Flags
      • Field width
      • Precision
      • Conversion specifier
        • first 3 are optional


 

d,i

Int

[-]ddd (where d are digits)

u

Unsigned int

ddd

o

Unsigned int

ddd 0-7

x

Unsigned int

ddd 0-9 a-f

X

Unsigned int

ddd 0-9 A-F


 

f

Double

[-]ddd.ddd

E,e

Double

[-]d.ddd e/E +/- dd

G,g

Double

-4<= exponent <precision (life f or e,E

c

Int

Treats int as unsigned char

Prints the character

S

Char*

Output chars from array up to '\0'

P

Void*

System dependant

Prints an address, usually in hexidecimal

N

Int*

Stores in variable; # of characters printed so far. No conversion

%

 

Writes a '%' sign


 

Length specifier in conversion specifier

  • h,l,L
  • you can have the h in front on the integer conversion specifiers
    • conversion specifier applies to short int (unsigned short int)
    • remember char / short args already promoted to int
    • convert arg to short before printing
  • the L,f,e,E,g,G conversion specifier applies to long double argument
  • do now use lowercase l or h with f,e,E,g,G

flags

  • field width
    • %5d
      • Decimal no sign
      • Field width of size 5
    • %-d
      • Fiend width 5
      • '-' is a flag
        • Left jusitication
    • %*d
      • Take next arg as field width
      • Scanf("%*lf, …)
        • * in scanf the * says read a double from input

Precision

  • After the period
  • %.5d
    • Min # digits to output, pad left w/ 0's
  • %.5f
    • # of fraction digits
  • %.5g
    • Max # of significant digits
  • &.5s
    • Max # of characters to print from the string

Flags

  • -
    • Left justify
  • 0
    • Pads with 0's
  • +
    • Forces explicit plus sign
  • ' ' (space)
    • Use a space instead of plus sign in the output
  • #
    • Changes conversions
    • 0 à leading 0
    • %#F
      • The decimal sign is printed even if there is nothing after it

EATS 1011 Lecture 10

Clouds

Nacreous clouds

  • A form of PSC (~10 microns)
  • Formed by waves over mountains
  • Text and other locations: nacreous clouds
  • PSC
    • Polar stratospheric clouds
  • Located about 15-25km
  • Winter polar stratosphere is very cold 180-190 K
  • HNO3 and water form ice clouds
  • Ice surfaces catalyse conversion of HCL to CL which attacks ozone and creates ozone hole
  • Contains:
    • H2O, h2SO4, HNO3, HCL

Noctilucent Clouds

  • Only appear in polar regions
  • Size ~.1 microns or smaller
  • Very thin layer clouds:
    • Hard to see over head
    • Only visible at twilight or later w/ a long path for illumination
  • At the summer mesopause
  • Very cold ~100-140 K
    • 173 to 133 degrees celcius
  • Frozen water
  • Ccn probably meteoritic dust
  • Wave structures revealed in ice formation
  • Can be warning of increased methane (CH4)`

Lapse Rates

  • Environmental
  • Γe environmental lapse rate
    • dT/dz = ΔT /ΔZ = - Γe
    • 'dry' adiabatic
      • g/Cp = Γdry
    • 'moist' adiabatic
      • g/Cp = Γmoise
    • ΓMoist < ΓDry
  • Depends on the planet and the major gas
  • AIR PARCEL(AP)
    • Think of an isolated unit of air maintaining its integrity
    • This doesn't work for long because of exchange of molecules etc
  • Lapse rate is how the temp is going to change in height
  • A steep lapse rate means large temperature change
  • Adiabatic
    • No exchange of energy with outside
  • Cooling
    • Important in Cloud formation and rain
  • Mean global rate
    • ~6.5 C/Km
    • Inversion, temperature increases with height
  • Specific heat @ constant pressure Cp energy add to raise temp 1Celsius for 1kg @ constant pressure
  • Specific heat @ constant Volume Cv energy add to raise temp 1Celsius for 1kg @ constant pressure
    • Cp(air) = 1007 J/kg/Kelvin
      • For one Kg you have to have supply 1007 joules for 1 degree celcius difference
    • Cv(air) = 700 J/kg/Kelvin
  • − T2 ) / (Z2 – Z1) = (-g)/Cp
    • Dry adiabatically
  • -(T1MCp)
    • Extract heat
  • + Mg(z2-z1)
    • Add potential energy
  • + CpMT2
    • Add heat

Thursday, January 31, 2008

CSE2031 Lecture 8

  • When creating a struct no space is allocated
  • typedef
    • Make a new type name
  • Typedef double grade
    • "grade" is now a new type
    • grade g1 = 3.5
      • Grade can be used whenever double is used
    • Typedef unsigned int size_t;
    • Typedef void (*_sighandler_t)(int)
  • Pointers to structs
    • Structpoint p1;
    • Structpoint* pp;
    • pp = &p1;
    • the name of a struct is not a pointer to the beginning of the variable
    • p1.x = 9
    • *pp.x = 9 //doesn't work
      • Because dot operator has precedence over *
    • (*pp).x = 9
      • // will properly dereference the struct
    • ppàx = 9
      • same as (*pp).x =9 only this is proper
  • self referential structures
  • if you don't use malloc calloc etc it is put on the stack not the heap
  • look in back of the book under IO
    • c library IO(buffered)
    • this is the buffer which input and output is written to
    • int getChar(void)
    • int putchar(int)
    • scanf
    • printf
  • file access
    • FILE
      • The way you create one is
        • FILE * fp
        • fp = fopen("filename", mode);
        • mode is
          • read write and append
          • a 2 character string
          • char*
        • instead of filename you can use
          • "rb"
          • "wb"
          • Ab"
          • "rt"
          • "wt"
          • "at"


 


 


 

//creating a structpoint//

--------------------

structpoint{

    int x;

    int y;


 

    }

---------------------------


 

structpoint p1;

p1.x = 5;

p1.y = 6;

------------

or


 

structpoint p1 = {5,6};

----------------------------------

or

structpoint{

int x;

int y;

}

p1;

p1.x = 5

p1.y = 6;

//you can make a new struct doing it this way

--------------------------------------

struct{

int x;

int y;

}

p1.x = 5;

p1.y = 6;

//cannot make a second struct doing it this way

---------------------------------------

typef unsigned int size_t;

typedef void (*_sighandler_t)(int)

--------------------------------------

typedef structpoint {

int x;

int y;

}

point;

/*now "point" is the name of a type

* it can have pint p1;

*instead of structpoint p1

*/

--------------------------------

/* self referential structures*/

struct listNode{

int value;

struct listNode* next;

}

--------------------------------

struct treeNode{

int value;

struct treeNode* left;

struct treeNode* right;

}

------------------------------------

or

--------------------------------------

typedef structTNode* TreePtr

typedef structTNode{

int value;

TreePtr left;

TreePtr right;

}TreeNode


 

-----------------------------------------

TreePtr root = (TreePtr)malloc(sizeof(TreeNode));         // - do not do this instead - sizeof(int) + 2*sizeof(TreePtr)

root->value = 5;

root -> right = (TreePtr)malloc(sizeof(TreeNode));

root -> right ->value=2;

root -> right->right =null;

root -> right ->left = null;

/*creates a binaryTree with root starting point at 5 pointing to a 2 on its right side that has no strings after it*/

--------------------

struct item{

double price;

char name[50];

}

item x1;

strcpy(x1,name, "Notebook");

---------------------------

struct item{

double price;

char* name;

}

item x1;

x1.name = "notebook";

-----------------------------------

fprintf(fp,...);

fscanf(fp,...);

fclose(fp);

ferror(fp);

intfeof(fp); //if you reached end of file on that file

fflush(fp);

fseek(fp,...);

fsetpos(fp,...);

--------buffered standard output under this line--

stdin

stdont

stderr

---------unbuffered under this line---


 

STDIN_FILENO         0

STDOUT_FILENO        1

STDERR_FILENO        2

--------------------------------------------------

#include <stdio.h>

#include <unistd.h>

int main(void)

{

printf("a");

write(1, "X", 1);

fprintf(stdout, "B");

write (1,"Y", 1);

printf("C");

write(1, "Z\n", 2);

printf("\n");

return 0;

/*output is

XYZ

ABC

this is becuase it's buffered

/*

}

                        

Tuesday, January 29, 2008

CSE2031 Lecture 7

void* ß malloc (int n)

int *p;

p = malloc (50 * sizeof(int));

Or

p = (int*) malloc(50*sizeof(int));

if((p=malloc(..) ) == null)

{

…exit(1)

}

free(p); //deallocate this space;

  • calloc enters 0's in memory for allocated space
  • go to man 3 malloc
    • talks about malloc calloc and realloc
    • realloc
      • allows you to resize memory partition previously allocated
  • arrays in C don't know how long they are

int x //declares an int

int f(int a , double b) // function that returns an int

int *f(int a, double b) //pointer to a unction that returns an int

int (*f)(int a, double b )//declares a function that takes parameters and returns an int


 


 


 


 


 


 


 


 


 

#include <stdlib.h>

#include <stdio.h>

#include <string.h>


 

int strCompare(const void *, const void *);

int intCompare(const void* p1, const void* p2);

int main(void)

{

char* A[] = {"30","3","20","2","0","5","10","1","40","4", "5"};

    for (i = 0;i<11;i++)

{

printf("%s ", A[i[);

}

putchar('\n');

qsort(A, sizeof(A)/sizeof(char *), sizeof(char *), strCompare);

return 0;

}

int strCompare(const void*p1,const void*p2)

{

int n = strcmp(*(char**)p1, *(char**)p2); //

if (n<0) return -1;

if (n>0) return 1;

return 0;

}

int intCompare(const void*p1, const void*p2)

{

int n1 = atoi(*(char**)p1);

int n2 = atoi(*(char**)p2); // atoi casts string to integer

if (n1<n2) return -1;

if (n1>n2) return 1;

}


 

(A, ... , cmp)

//int cmp(const void *p1, const void *p2)

//{int n1 =

int n2 =

if(n1<n2) return -1;

if(n1>n2) return 1;

return 0;


 


 

c struct

  • struct point {int x, int y};
    • point is the structure tag