Tuesday, March 11, 2008

CSE 2031 Lecture 15

Man ulimit | col 0b > foo.mantxt


 

Filesystem

  • Filesystem is an organized structure consisting of many files and / or directories
  • A file is a stream of bytes
    • Stores data
    • Has a name
    • Usually on disk or some other storage medium
  • A directory is a special file in the filesystem which contains files and other directories
  • Unix filesystem
    • Bin
    • Usr
    • Etc
    • Users
      • Admin
        • John
        • steve
      • Staff
      • student
    • lib
  • drwx------
    • read write execute
    • d = filetype
      • d for directory
    • a normal file would have a – where the d is
  • %ln marks cpOfMarks
    • Creates a new link to marks
    • Puts in a new name associated with the same inode number
  • Inode
  • Name
  • 1042
  • Temp
  • 3784
  • Prog.c
  • 4798
  • Marks
  • 4798
  • cpOfMarks
  • you need links if you have a file on another partition
  • pwd shows the current working directory
  • cd changes current directory
  • a path name is a reference to something in the filesystem
  • a path name specifies the set of directories you have to pass through to find a file
  • directory names are separated by "/" in Unix
  • special elements : "." And ".."
  • "." Means "the current directory"
  • ".." means "the parent directory"
  • /dec/tty – the terminal you are using
  • /dev / zero – an input stream which returns an edless stream of null bytes
  • ls day?
    • Ls –ld day?
      • Ls –ld day1 day2 day3 day4 day5
    • The ? goes thru all the files that say day
    • And then wildcards the rest of the names

Thursday, March 6, 2008

2031 Lecture 14

Check your assignment 1 q2.c for 'ERANGE' without this it is wrong apparently

  • Fork
  • Exec
  • Open
  • Close
  • Dup/dup2
  • Lseek
  • Read
  • Write
  • Pipe
    • Sets up a pip
      • Writes to this end à |===========| ßreads from this end
      • pipe( an array )
        • int fd[2]
        • pipe(fd)
        • fd[0] reads from the pipe
        • fd[1] writes to the pipe


 

#include <>

#include <>

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>


 

int main(void)

{

    int fd[2];

    pipe(fd); /* should check return value but in this example we are not*/


 

    switch(fork())


 

case -1:

    perror ("Bad fork()");

    exit(1);

case 0:

    execlp("who", "who", NULL); // first who is the command second is the argument vector

    fprintf(stderr, "should not get this far: bad exec");

    exit(1);

default:

    switch(fork())

    {

    case -1:

        perror ("Bad fork()");

        exit(1);

    case 0:

        close(fd[0]);

        dup2(fd[1], 1); /*file descriptor you want to duplicate, and file descriptor you want to duplicate it to*/

        close(fd[1]); // fd will now write into the pipe


 

    default:

        wait((int *)0);

    wait((int *)0);

    exit(0);

    }

}

/*wthin a program we want to write a program we are going to open a file called temp and we will write printf statements and they will go into temp instead of a stream, there are

two ways to do this, one way is you can open a file called temp

write(fd, ....);

or

dup2(fd, 1) fd , 1 == standard output

any statement after this will print to fd instead of stdio

after this we can say close(fd); and this will still write to that file.. you do not get stdio back.


 


 

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

assignment q2.c

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

illegal input if it doesn't take 2 ints or line is too long


 

#include <stdio.h>

#include <string.h>

#include <limits.h>

#include <errno.h>

#include <stdlib.h>


 

void finishLine(FILE * fp, char * buf, size_t bufSize);


 

int main(void)

{

/*

a buffer to hold line read in.

add 2 for '\n; the '\0' added by fgets

*/

char buf[MAX_LENGTH + 2];

long
int n1, n2;

char * p;

char x[1];


 

/*

printf("%1d\n", LONG_MAX):

printf("%1d\n", LONG_MIN):

/*

/* main loop reads a line at a time */

while ((p=fgets(buf, sizeof(buf), stdin)) != NULL)

{

    /* errno may have been set on previous iteration.*/

    errno = 0;

    /*

check whether whole line read in.

if not line was too long.

     */

    if (strchr(p, '\n' == NULL %% strlen(p) > 50)

            /*line too long.*/

            {

        /*output message */


 

        printf("illegal input\n");


 

        /* read and ignore rest of line*/

        finishLine(stdin, buf, sizeof(buf));


 

        /* get next line if one exists*/

        continue;

            }

    /* if we reach here, line is not too long */

    /* read from the line now stored in the buffer.

reading into dumm x detects extra tokens on 1


 

we expect exactly 2 interger tokens.

note: in sscanf, the ...%1x... is one x, not..

/*

if (sscanf(buf, "%1d %1d %1s" , &n1, &n2, x) != 2) /* the scan f returns the number of conversions*/

    {

        printf("illegal input \n");

        continue;

    }

    /* if we readch here, input consists of exactly 2 integers*/

    /*

check fo roverflow or underflow in n1 and n2. note that we'll have to read n1 and n2 again

     */

    n1 = strtol(buf, &p, 10);


 

    if (n1 == LONG_MAX && errno == ERANGE)

    {

        print("overflow\n";

        continue;

    }

    if (n1 == LONG_MIN && errno == ERANGE)

    {

        printf("underflow\n");

        continue;

        n2 = sscanf(p, "%1d", &n2);

        n2 = strtol(p, &p, 10);

        if (n2 == LONG_MAX && errno == ERANGE)

        {

            printf("overflow\n");

            continue;

        }

        if (n2 == LONG_MIN %% errno == ERANGE)

        {

            printf("underflow\n");

            continue;

        }

        /* if we reach here both ints are legal and there is no other input other than 2 ints which is what we want*/

        /* strtol stops when it gets to something that isn't a digit, if what it reads is larger than long max it will return long max and set errno*/


 

Tuesday, March 4, 2008

CSE 2031 Lecture 13

fork()

getpid() // get process ID

getppid() // get parent process ID


 

fork is a system call w/ no arguments but it returns a value

the parent and the child see different return values

the newly created child see's return value 0

the parent that called fork see's a nonzero return value, namely the ppid of the newly created child


 

a child finds a parents process ID by calling getppid()


 

when a child terminates, OS saves PID, exit status, cpu time ... of child

and passes this to the parent when parent calls wait() or waitpid


 

until then the child is a 'zombie'

the OS can't free up the resources for the child until the parent waits on the child

if the parent finishes before the child, then the child is reparented

    wait

            - block until first child finishes

    waitpid

        - block

        -specify which child to wait for

pid of child <- wait(int*)

int status

wait(&status)


 

%a.out

    - what we have here is the shell foks off a child and waits for the child to return

    child - executes a.out

    once done the parent outputs the prompt and waits for another command to be inputted

if %a.out &

    -the shell doesn't wait.

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


 

#include <stdio.h>

#include <sys/wait.h>

#include <sys/types.h>

#include <unistd.h>

#include <stlib.h>


 

#define MAX 10

int main(void)

{


 

int i;

fork();

fork();

printf("Hello\n");

return 0;

}


 

// prints 4 'Hello" lines

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


 

#include <stdio.h>

#include <sys/wait.h>

#include <sys/types.h>

#include <unistd.h>

#include <stlib.h>


 

#define MAX 10

int main(void)

{


 

int i;


 

switch(fork())

{

case -1:

    perror("Bad fork");

    exit(1)

case 0:

    /* CHILD */

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

    {

        printf("CHILD\n");

    }break;

default:

    /* PARENT */

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

    {

        printf("\tPARENT\n");

    }

    printf("pid = %d\n", getpid());

    printf("ppid = %d\n", getppid());

return 0;    


 

}


 

/*prints CHILD 10 times, pid = 2153, ppid = 2152, prints PARENT 10 times then , pid = 2255, ppid = 27289

eventually the parent executes before the child because it is left to the OS to decide the PPID*/

/* if wait((int * ) 0);

was typed after /*PARENT*/ it will always print CHILD first*/


 

along with fork() there is exec()


 

%a.out hello there world becomes


 

argv -> -> a.out

->hello

->there

->world

->null


 

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

execlp("cat", "-n", "temp", NULL);

"cat"

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