Chapter Summary Q Flashcards

1
Q

1: What is applications programming?

A

Programming of software to provide services for the user directly

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

1: What is systems programming?

A

Programming of software that provides services for other software or for the underlying computer system

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

3: What is a pointer?

A

It is a variable to store a memory address of another variable. They can be 4-8 bytes, and allow for Pass-by-reference.

Note that multiple pointers can point to the same address.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

3: What are two possible errors associated with pointers?

A

Segmentation fault/NULL Pointer: A pointer is pointing to NULL, crashes program.

Dangling Pointer: Pointer is pointing to random data (cruft data), will cause strange behavior and is difficult to find.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

3: How does a pointer to a array work?

A

A pointer to a array typically points to the first element of the array. As such the following is technically a pointer:

EXAMPLE:
int AR[30] = { ------ }
AR; //AR = pointer to AR[0]
//Also means:
AR == &AR[0];
AR+2 == AR[2];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

3: How does adding to arrays to increment work?

A

*AR+4 == AR[0]+4 //So the VALUE at [0] has been incremented by 4

vs.

*(AR+4) == AR[4]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

1: What are some things that the OS provides?

A
File I/O
Device I/O
Process Managements
Virtual Memory
Scheduling
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

1: What is a shell?

A

A command line user interface for accessing the OS

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

1: What are the three major Unix shells?

A

sh : bourne shell

bash: bourne again shell
csh: c shell

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

3: What are command line arguments and how are they used?

A

A command line argument is a variable inputed into a function/program from the command line b doing: ./program val1 val2 … valn

They are recieved in the programs main by:
int main(int argv, char *argc[]) {.....}

Where: argv = number of cmd-line inputs
argc = the string/character array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

1: What is a compiler?

A

Computer software that transforms source code written in one programming language into another

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

3: What does the size command do?

A

size results in a output of:

text = Text segment
data = Init data size
bss = Unit data size
dec = sum of text+data+bss in base 10
hex = same as dec but in base 16
filename = name of .exe
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

1: What is the basic format for formatting variables with printf

A

%[flags][width][.precision][length]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

1: What is the path from source code to a running program?

A
.c source file
--compile
.o object file
--link
executable file
--run
program is running!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

3: What is stack overflow?

A

It is a error which occurs when a repeating function call occurs which depletes all free memory and fills the stack

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

1: What is the basic format for formatting variables with printf

A

%[flags][width][.precision][length]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

3: How does adding to arrays to increment work?

A

*AR+4 == AR[0]+4 //So the VALUE at [0] has been incremented by 4

vs.

*(AR+4) == AR[4]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

1: When formatting with %_, which characters denote:
- an integer?
- an unsigned integer?
- a float with 6 decimal precision?
- a float with exponential precision?

A

Integer: %d
Unsigned Int: %u
Float with 6 dec.: %f
Float with exp. prec.: %g

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

1: When formatting with %_, which characters denote:
- a char?
- a string?
- a hexadecimal?
- an octal?

A

Char: %c
String: %s
Hexa: %x
Octal: %o

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

1: How does the precision modifier affect the format when applied to:
- a float
- an exp. float
- a string
- %d, %u, %o, %x, %X

A
  • float: precision is how many decimal places
  • exp. float: precision is how many digits total
  • string: precision is how many characters displayed
  • how many leading zeroes are shown
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

1: What does the “continue” command do?

A

skip the current item in a for loop and go on to the next item

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

1: How do you define a constant in C?

A

define DAYS_IN_YEAR 365

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

3: If a dynamically allocated variable was modified how would you allocate it and free it?

A
//Allocate
int *a;
int *aTemp;
a = aTemp = malloc(sizeof(int));

//Free
free(aTemp);
free(a);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

1: What does the “break” command do?

A

break out of the current innermost loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

3: What are other ways to dynamically allocate memory?

A

malloc(SIZE OF MEMORY) = Assigns a random chunk of memory, be have cruft.

calloc(NUMBER OF ITEMS, SIZE OF ITEM) = Assigns a cleared random chunk.

realloc(PTR FROM C/MALLOC, NEW SIZE) = Re-sizes a previous malloc or calloc. If given SIZE is 0 it de-allocs the PTR. If given PTR is NULL it works the same as a malloc.

*If these fail they return NULL.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

3: How are address assigned to bytes of blocks representing a var in the HEAP?

A

The heap assigns a BLOCK of addresses to a var depending on its required size (i.e. int = 4 bytes, char = 1 byte).

However a pointer only points to the FIRST address of the block, but will return the actual data from the whole block of addresses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

3: What is a pass-by-value in C?

A

When a non-primitive data type is passed to a function directly. The function will then copy the passed var, manipulate its copy, returns the copy, and discards its copy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

3: What is a pass-by-reference in C?

A

When a pointer to a variable is passed to a function. The function can then de-reference the pointer and manipulate the variable directly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

3: What are command line arguments and how are they used?

A

A command line argument is a variable inputed into a function/program from the command line b doing: ./program val1 val2 … valn

They are recieved in the programs main by:
int main(int argv, char *argc[]) {.....}

Where: argv = number of cmd-line inputs
argc = the string/character array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

1: How do you use the random function?

A

include

rand() function use:

srand(time(NULL));

double value = rand()/(double) RAND_MAX

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

1: How do you make an array in C?

A

int ages[ ]={34,20,18};

int ages[8]={34,20,18}; //the rest are filled with 0s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

3: What is a dynamic array?

A

It is a array which can grow and shrink but does not require the overhead of a linked list. Defined by:

typedef struct {
int size;
Person **p;
} ArrayT

ArrayT myArr;
myArr.size = 100;
myArr.p = malloc(100*sizeof(struct ArrayT*));
for (...) {
   p[i] = ...
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

3: What is a function pointer and how do you make one?

A

It is a var that stores a pointer to a functions code in memory so it can call the function even by passing it as a param somewhere else. Similar to eventhandlers in JAVA.

//Pointer:
void (*fPtr) (int, float);
//Fnc pointed to:
void add (int X, float Y) {
....
}

//Call pointer/fnc by:

  1. add(2, 5.0); //Normally
  2. fPtr(2, 5.0); //As fPtr
  3. (*fPtr) (2, 5.0); //De-refed
  4. int (*fPtr[N] (int, int) = {fnc1, fnc2, …fncN); //As a array
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

2: What is 00010001 in octal?

A

21 [base 8]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

2: What is 10101100 in hexadecimal?

A

AC [base 16]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

2: What is a bit model?

A

A method if interpreting a sequence of bits

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

5: What is a multi-process?

A

It is when multiple processes execute simultaneously while communicating. This can even include multiple copies of the same program running.

Allows for scheduling of unique process for a group of many tasks. Can also assign specific resources, allowing for decrease in bottleneck and increase in efficiency.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

5: What is a multi-thread?

A

It is a single process with multiple control flows, so multiple tasks can be performed by one CPU which shares the same virtual memory, address space and resources.

Unlike a multi-process, here tasks are usually dependent on each other but must be synchronized to avoid error conditions.

Multi-threading allows for decreased complexity while still allowing multiple events to be handled at the same time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

1: What should functions do?

A

Take data in, do something, return a results
Have a single purpose
Encapsulate
Be Reusable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

5: What is a problem with sharing resources in concurrent computing?

A

If multiple processes or threads require the same resources then sharing must be coordinated to avoid faults. This can be done by “locking up” the resource with a semaphore.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

5: What is a semaphore and what is a mutex?

A

Semaphore: A variable used to control access to a resource by multiple processes. Waiting threads/processes must be signaled by the thread/processes currently with the resource before they can access it.

Mutex (Mutual exclusion object): A program object which is a specific kind of semaphore where a thread/process currently “holding” the mutex can access it, this is done with binary count.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q
2: Floating point numbers have some special cases. What are the sign bits, exponent bits, and mantissa bits for the following special cases?
0
infinity
-infinity
NaN
A
  • | 00000000 | all zeros
    0 |11111111 | all zeros
    1 |11111111 | all zeros
  • |11111111 | non-zero
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

1: What is the coding convention for naming Data Types?

A

PersonType

BankAccount

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

2: What are the ASCII and unicode bit models?

A
Maps binary numbers to characters.
32-> space
62->A
48->0
00->NULL
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

2: What are the bases of each of the following number systems? What digits/chars does each use?

Binary
Octal
Decimal
Hexadecimal

A

Binary 2
0 1

Octal 8
0 1 2 3 4 5 6 7

Decimal 10
0 1 2 3 4 5 6 7 8 9

Hexadecimal 16
0 1 2 3 4 5 6 7 8 9 A B C D E F

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

5: How can a process be manually controlled?

A

This can be done through shell commands such as:

& - Append to end of command to hide result
ps - List PID's
kill (PID) - Kills specified PID
jobs - Lists all running jobs 
fg - Continue last suppressed program
bf - Same as fg but in background
CTRL-Z - Suppress a program
CTRL-C - Kill foreground program
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

5: How can a process be controlled in code?

A

Instead of shell commands functions can be used:

FORK - fork() will create a child process from that point in the code, it returns the childs PID. A recursive or infinite number of forks is a fork-bomb this will crash the program.

SLEEP - usleep() will sleep a program for a specified number of seconds

PID - getpid() will return the PID of the current process that is running the code

EXEC - This has many variations and allows different code to run with the same PID, causing code to go run a different program instead and not continue to the next line.

WAIT - wait() Waits for a specified child to return, will return the child PID which was a output param.

EXIT - exit() Will exit the current process

WAITPID - waitpid() will wait for a specified PID (child process)

SYSTEM - system() allows us to run a specified shell command, and returns value of system call or -1. i.e. can run system(“ls -a”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

5: What is Inter-process Communication (IPC)?

A

It is the sending and receiving of information between processes, there are two main methods of doing this which are signals and sockets.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

5: In IPC what is a signal?

A

It is a int-value sent by one process to another on the SAME host machine. It can be used to represent basic commands.

C uses a fixed set of signals found in signal.h, two of which can be user defined:

  • # define SIGUSR1
  • # define SIGUSR2

To code a signal do:

i) Install signal handler
ii) Send signal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

5: In IPC what is a socket?

A

It is a alternate IPC method that acts as a endpoint for sending and receiving data.

It works by assigning a IP to each host and a port number to each process.

It then uses two layers to handle data:
Transport Layer: A conceptual layer to indicate how data is sent, either TCP or UDP
Network Layer: The method of sending packets from src-host to dest-host.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

3: How do you remove from the stack?

A

First all local vars are removed.

Then it returns control of memory addresses corresponding to return address and pops of the stack.

Params are then removed from the stack.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

3: What is dynamic memory allocation?

A

It is the manual allocation and de-allocation of memory for variables into the heap.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

5: What is the TCP Transport Protocol, how does it work?

A

It is a Client-Server Model which has a server process receiving and actively listening and a client process sending/performing tasks.

Steps to build a server:
1. Include sys/socket.h
2. socket(domain, type, TCP)
3. bind(serv sock ,address, address_length)
4. listen(serv sock, back log)
while (true) {
   5. accept(serv sock, client addr, client 
   addr_length)
   while (client up) {
       6. recv(client sock, buffer*, buffer_length, 
       flags)
       7. send(client sock, buffer, buffer_length, 
       flags)
    }
    close(client)
}
close(server)

Steps to build a client:
*Same except use connect() NOT bind(), set sock_addr to inet_addr(“127.0.0.1”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

5: What is the UDP Transport Protocol, how does it work?

A

It is a Client-Server Model which has a server process receiving but NOT actively listening and a client process sending/performing tasks.

Steps to build a server:
1. Include sys/socket.h
2. socket(domain, type, TCP)
3. bind(serv sock ,address, address_length)
while (true) {
4. accept(serv sock, client addr, client
addr_length)
5. select(num Desc, read FDS, write FDS, except
FDS=NULL, timeout)
6. recvfrom(sock, buffer, buffer_length, flags,
client_Addr, clientAdd_Length)
7. sendto(sock, buffer, buffer_length, flags,
client_Addr
, clientAddr_Length)
close(client)
}
close(server)

Steps to build a client:
*Same method as server.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

5: What is a thread?

A

It is the running of multiple copies of the same process (rather then communication between processes). A thread is therefore a sequence of programmed instructions that can be managed independently by the OS.

Threads decrease chances for race conditions and deadlocks.

Fork() can be used on a thread to make children threads, and their timing is scheduled by the kernel.

It is faster the switch threads then it is to switch processes

56
Q

5: What are the components of a thread?

A

Each thread has the following:

  • A unique thread ID
  • Memory in Stack segment (function call stack)
  • Program counter, counting program instructions

All threads share:

  • Address space of processes
  • Memory in Data segment
  • Memory in Code segment
57
Q

3: If a dynamically allocated variable was modified how would you allocate it and free it?

A
//Allocate
int *a;
int *aTemp;
a = aTemp = malloc(sizeof(int));

//Free
free(aTemp);
free(a);

58
Q

5: How are semaphores used to stop improper context switching in a thread?

A

The semaphore is used as a counter with 0 and non-0 values to indicate use of resource. Create by:

  1. # include semaphore.h
  2. sem_t semaphore;
  3. sem_init (&semaphore, use b/ threads = 0, inti val = 1)

4 .sem_wait(&semaphore); - Fnc waits on semaphore, if free semaphore value is decreased

  1. sem_post(&semaphore); - Fnc to release lock, will increase semaphore value
59
Q

3: What are other ways to dynamically allocate memory?

A

malloc(SIZE OF MEMORY) = Assigns a random chunk of memory, be have cruft.

calloc(NUMBER OF ITEMS, SIZE OF ITEM) = Assigns a cleared random chunk.

realloc(PTR FROM C/MALLOC, NEW SIZE) = Re-sizes a previous malloc or calloc. If given SIZE is 0 it de-allocs the PTR. If given PTR is NULL it works the same as a malloc.

*If these fail they return NULL.

60
Q

2: What is the Sign-Magnitude bit model? How do you use it to add binary numbers?

A

Model for allowing negative decimal (whole) numbers
Range: -127 to +127

If the sign bits are the same, add magnitudes and leave the sign bit intact

61
Q

2: What is the two’s compliment bit model? How do you use it to add binary numbers?

A

Allows negative and positive decimal numbers

19 ->00010011
flip bits ->11101100
add 1 ->11101101
That last line is -19!

In this model, if the most significant (left) bit is 1, then the number is negative, and if it is 0 then the number is positive

To find the magnitude of a negative number, flip the bits and then add 1

62
Q

2: What is the fixed point bit model? How do you use it to represent real numbers?

A

It is a binary point system

111010.101

63
Q

2: What is the floating point bit model? How do you use it to represent real numbers

A

Scientific notation for numbers is
+/- M x B^E (M=mantissa, B=base, E=exponent)

For example
284 = 100011100(B2) = 1.000111 x 2 ^ 8

Sign Bit: 0
8 bit exponent: 00001000 (B2) = 8
23 bit Mantissa: (1)00 0111 0000 0000 0000 0000
(the first will always be 1 so we drop it)

For double types, the exponent is 11 bits and the mantissa is 52

64
Q

2: How do you add floating point numbers?

A
  1. Look at their exponents. Find E1 - E2 = N
  2. If N is negative, shift binary point in M1 N spots to the left, (if positive go to the right)
  3. Now they have the same exponents so you can add them and keep the exponents in tact
65
Q

2: What are the ASCII and unicode bit models?

A
Maps binary numbers to characters.
32-> space
62->A
48->0
00->NULL
66
Q

3: What is a linked list?

A

A linked list is a data structure similar to array, except it can be dynamically grown or shrunk. However elements are not contiguous so access can be slower then in a array.

67
Q

3: What is a singly-linked list?

A

A SL is a list that has a head (sometimes a tail) and each node has a pointer to the next node.

68
Q

3: What is required to make a linked list?

A
  1. A struct representing the data type being stored
  2. A node/list struct, with next/prev pointers and a data pointer
  3. A print list function
  4. A add and a remove function
  5. A free function

*This promotes encapsulation

69
Q

3: How do you insert into a list?

A
  1. Into empty list
  2. Into front (new head)
  3. Into back (new tail)
  4. Into middle
70
Q

3: How do you remove from a list?

A
  1. From a empty list (do nothing)
  2. Remove the last element
  3. From the front (update head)
  4. From the back (update tail)
  5. From the middle
71
Q

3: What is a doubly linked list?

A

It is a linked list with a head/tail but each node is recursive in that it has a pointer to the next AND prev node.

This requires nearly 2x the overhead as a singly linked list.

72
Q

3: What is a dynamic array?

A

It is a array which can grow and shrink but does not require the overhead of a linked list. Defined by:

typedef struct {
int size;
Person **p;
} ArrayT

ArrayT myArr;
myArr.size = 100;
myArr.p = malloc(100*sizeof(struct ArrayT*));
for (...) {
   p[i] = ...
}
73
Q

3: What is a function pointer and how do you make one?

A

It is a var that stores a pointer to a functions code in memory so it can call the function even by passing it as a param somewhere else. Similar to eventhandlers in JAVA.

//Pointer:
void (*fPtr) (int, float);
//Fnc pointed to:
void add (int X, float Y) {
....
}

//Call pointer/fnc by:

  1. add(2, 5.0); //Normally
  2. fPtr(2, 5.0); //As fPtr
  3. (*fPtr) (2, 5.0); //De-refed
  4. int (*fPtr[N] (int, int) = {fnc1, fnc2, …fncN); //As a array
74
Q

2: What is a bit operator?

A

An operator that takes one or two numbers and performs an operation on the bits of those numbers

75
Q

2: What are the different bit wise operators in C?

A

~ NOT: inverts bits
& AND: performs AND b/w every bit
| OR: performs OR b/w every bit
^ XOR: performs XOR b/w every bit
» right shift: shifts bits into lower order/less significant bit positions
&laquo_space;left shift: shifts bits into high order/more significant bit positions

76
Q

2: What is a bit mask?

A

A sequence of one or more bits that you apply to another binary number to read, set, or clear the value of one or more bits

E.G
Set bit 2 of x
x = 19;//00010011
m=1<<2; // (00000001 ->00000100);
m=x|m;// 

00010011 OR
00000100
________
00010111

77
Q

4: What is a preprocessing directive? What are two examples?

A

include : compiler takes source code from included header file and inserts it right into your file

Any code that begins with a #

78
Q

4: What are the 3 steps in the compilation process?

A

1: Pre processing
2: Assembly code creation: translate source code into assembly code
3: Machine code creation: translate assembly code into machine code
Final “step” is linking

79
Q

4: What are the commands for linking files?

A

gcc -c linkEx1.c
gcc -c linkEx2.c

gcc -o linkExFull linkEx1.o linkEx2.o

80
Q

4: What is a makefile?

A

A text file that is used by the make command to automatically build executable programs & libraries from source code

all: linkEx1 linkEx2
[TAB      ]gcc -o linkExample linkEx1.o linkEx2.o
linkEx1: linkEx1.c linkEx1.h linkTypes.h
[TAB      ]gcc -c linkEx1.c
linkEx2: linkEx2.c linkEx2.h linkTypes.h
[TAB      ]gcc -c linkEx2.c
81
Q

4: How and where do you use variables in a makefile?

A

At the top of the makefile

OBJ = linkEx1.o linkEx2.o

$(OBJ)

82
Q

5: What is concurrent computing?

A

A form a computing where several computations are executed during overlapping periods rather then sequentially.

83
Q

6: What are the standard streams in C?

A

stdin - standard input == 0 (keyboard is default)
stdout - standard output == 1 (display is default)
stderr - standard error == 2 (display is default)

84
Q

5: What is a distributed system?

A

It is a program executing on multiple physical hosts over INTRANET or INTERNET.

This means TTCT is decreased since amount of resources is increased. However this requires more overhead in the form of a server and other equipment.

85
Q

5: What is a multi-process?

A

It is when multiple processes execute simultaneously while communicating. This can even include multiple copies of the same program running.

86
Q

6: What are the different modes for the fopen() function?

A

FILE* fopen(const char *filename, const char *mode);

Modes:
“r”: reading a file that must already exist
“r+”: opens a file for reading and writing
“w”: writing a file, can make a new one if it doesnt exist
“w+”: creates a new file for reading and writing
“a”: appending to file, can make a new one if it doesnt exist
“a+”: opens a new file for reading and appending

87
Q

6: What are input, output, and streams?

A

input: transferring bytes from data source to a program
output: transferring bytes from a programs to a data sink
streams: transferring of bytes (i/o)

88
Q

6: What are the standard streams in C?

A

stdin - standard input == 0 (keyboard is default)
stdout - standard output == 1 (display is default)
stderr - standard error == 2 (display is default)

89
Q

5: What are three issues with concurrent computing?

A
  1. Sharing resources
  2. Deadlocks
  3. Race conditions
90
Q

6: What functions can you use to read and write binary files?

A

size_t fwrite(const void *dataPtr, size_t size, size_t n, FILE *fd);

size_t fread(void *dataPtr, size_t size, size_t n, FILE *fd)

91
Q

6: What functions can you use to read and write text files

A

fprintf();
fscanf();

AND

size_t fwrite(const void *dataPtr, size_t size, size_t n, FILE *fd);

size_t fread(void *dataPtr, size_t size, size_t n, FILE *fd)

92
Q

6: What are some pros and cons of using TEXT data vs. BINARY data?

A

BINARY is faster to access than TEXT
BINARY requires less storage than TEXT
BINARY you can write full structs
TEXT you must write each field individually
BINARY has a low compression ratio (gets bigger)
TEXT has a high compression ratio (gets smaller)
TEXT data is easier to recover than BINARY data
TEXT data is easy to read

93
Q

6: What are the stream-related library functions? How do they affect the portability of a program?

A
int open (const char *path, int flags);
int close(int fileDescriptor);
ssize_t write(int fileDescriptor, const void *buffer, size_t count);
ssize_t read(int fileDescriptor, void *buffer, size_t count);

They are OS dependent so they may make your program non-portable

94
Q

6: What are the different modes for the fopen() function?

A

FILE* fopen(const char *filename, const char *mode);

Modes:

95
Q

6: What does fopen return if there are no errors?

A

FILE* : file handle/descriptor

returns 0/NULL ptr if an error has occurred

96
Q

6: What does fclose return if all went well?

A

0 if no errors

EOF if errors occurred

97
Q

6: What do the following functions do?
ferror(FILE *fd);
fclear(FILE *fd);
feof(FILE *fd);

A

ferror checks if the file’s error flag is set
fclear clears the file’s error flag
feof checks if the EOF has been reached

98
Q

5: What is a problem with deadlocks in concurrent computing?

A

This occurs when multiple threads/processes are all blocked because they have to wait for a resource or a condition which will never occur. This is causes by improper use of semaphores can be the result of bad code or unseen conditions.

99
Q

5: What is a problem with race conditions in concurrent computing?

A

It is a timing problem in which the correctness of a program depends on one thread reaching a certain point in the control flow before another thread. If this order is broken the program can crash.

100
Q

5: What is process management and what is responsible for it?

A

It is the allocating of resources, protecting resources, enabling sharing and synchronization.

It is the job of the OS, but can also be done through shell commands and system calls.

101
Q

5: What does a process have when it is created?

A
  1. Process ID (PID) = ID unique to the process
  2. Parent Process ID (PPID) = ID unique to the parent process that created it
  3. Access space and Virtual Memory = Its own part of the code segment, data segment, stack, and heap
  4. Control Flow
102
Q

5: How can a process be manually controlled?

A

This can be done through shell commands such as:

&amp; - Append to end of command to hide result
ps - List PID's
kill (PID) - Kills specified PID
jobs - Lists all running jobs 
fg - Continue last suppressed program
bf - Same as fg but in background
CTRL-Z - Suppress a program
CTRL-C - Kill foreground program
103
Q

6: What functions can you use to read and write text files

A

fprintf();
fscanf();

AND

size_t fwrite(const void *dataPtr, size_t size, size_t n, FILE *fd);

size_t fread(void *dataPtr, size_t size, size_t n, FILE *fd)

104
Q

5: How can a process be controlled in code?

A

Instead of shell commands functions can be used:

FORK - fork() will create a child process from that point in the code, it returns the childs PID. A recursive or infinite number of forks is a fork-bomb this will crash the program.

SLEEP - usleep() will sleep a program for a specified number of seconds

PID - getpid() will return the PID of the current process that is running the code

EXEC - This has many variations and allows different code to run with the same PID, causing code to go run a different program instead and not continue to the next line.

WAIT - wait() Waits for a specified child to return, will return the child PID which was a output param.

EXIT - exit() Will exit the current process

WAITPID - waitpid() will wait for a specified PID (child process)

105
Q

5: What is Inter-process Communication (IPC)?

A

It is the sending and receiving of information between processes, there are two main methods of doing this which are signals and sockets.

106
Q

6: What is sequential access of files?

A

always start at the beginning of the file and traverse through to get to where you want

107
Q

6: What is random access of files

A

don’t have to start @ beginning, can jump anywhere

108
Q

6: What is a file marker?

A

It indicates where in the stream the next byte is to be read from/written to

109
Q

6: What functions can you use to read, change, and reset the file marker?

A
int ftell(FILE *fd) -> where the file marker is
inr fseek(FILE *fd, long int offset, int whereFrom);

whereFrom:
SEEK_SET=0==beginning
SEEK_CUR=1==current pos
SEEK_END=2==end of file

int rewind() -> reset file marker back to start of file

110
Q

5: In IPC what is a signal?

A

It is a int-value sent by one process to another on the SAME host machine. It can be used to represent basic commands.

C uses a fixed set of signals found in signal.h, two of which can be user defined:

  • # define SIGUSR1
  • # define SIGUSR2

To use a signal there is a series of steps:

i) Install signal handler
ii) Send signal

111
Q

5: In IPC what is a socket?

A

It is a alternate IPC method that acts as a endpoint for sending and receiving data.

It works by assigning a IP to each host and a port number to each process.

It then uses two layers to handle data:
Transport Layer: A conceptual layer to indicate how data is sent, either TCP or UDP
Network Layer: The method of sending packets from src-host to dest-host.

112
Q

6: What is a buffer? What function do you use to manually flush it?

A

an area of memory used to temporarily store data while it is being moved from one place to another

fflush()

113
Q

6: What is pipelining and how do you do it in the command line?

A

action of redirecting streams

< uses a specified file as stdin to program
> redirects stdout of program to a specific file
| redirects stdout from one program to stdin of another

114
Q

6: What is a pipe?

A

a system call that creates a one way communication link b/w two file descriptors

115
Q

6: What is pipelining and how do you do it in the command line?

A

action of redirecting streams

< uses a specified file as stdin to program
> redirects stdout of program to a specific file
| redirects stdout from one program to stdin of another

116
Q

7: What is the general format of declaring variables?

A

{storage class}{qualifier}{modifier}{data type} {name}[={init value}];

117
Q

5: What are the kinds of sockets?

A
  1. Stream sockets: A connection-based socket, must establish a connection before transmitting and closed at the end. Is good for reliable packet delivery. – Works with TCP
  2. Datagram sockets: Connection-less sockets that do not need to be established, data is sent when ready. This results in fast packet delivery, but packets can be corrupted, received out of order, lost, or delivered multiple times. – Works with UDP
  3. Raw sockets: This by-passes the transport protocol entirely.
118
Q

7: What are the different storage classes of variables?

A

Static: variable is stored in data segment (global memory)
when a compiler finds a static variable in the code that has already been initialized, it does not re-initialize it

Extern: indicates that a variable in global and it actually declared in another file

Register: tells compiler to store the variable in a register (in the CPU)
- faster to use and access

119
Q

5: What is the TCP Transport Protocol?

A

It is a Client-Server Model which has a server process receiving and a client process sending/performing tasks.

Steps to use are:
1. Include sys/socket.h
2. socket(domain, type, TCP)
3. bind(serv sock ,address, address_length)
4. listen(serv sock, back log)
while (true) {
   5. accept(serv sock, client addr, client 
   addr_length)
   while (client up) {
       6. recv(client sock, buffer*, buffer_length, 
       flags)
       7. send(client sock, buffer, buffer_length, 
       flags)
    }
    close(client)
}
close(server)
120
Q

5: What is the UDP Transport Protocol, how does it work?

A

It is a Client-Server Model which has a server process receiving but NOT actively listening and a client process sending/performing tasks.

Steps to build a server:
1. Include sys/socket.h
2. socket(domain, type, TCP)
3. bind(serv sock ,address, address_length)
while (true) {
4. accept(serv sock, client addr, client
addr_length)
5. select(num Desc, read FDS, write FDS, except
FDS=NULL, timeout)
6. recvfrom(sock, buffer, buffer_length, flags,
client_Addr, clientAdd_Length)
7. sendto(sock, buffer, buffer_length, flags,
client_Addr
, clientAddr_Length)
close(client)
}
close(server)

Steps to build a client:
*Same method as server.

121
Q

7: What content usually goes in a source file?

A
  • function implementations
  • global variable declarations
  • constants, types, and function prototypes specific to that file
122
Q

5: What is a thread?

A

It is the running of multiple copies of the same process (rather then communication between processes). A thread is therefore a sequence of programmed instructions that can be managed independently by the OS.

Threads decrease chances for race conditions and deadlocks.

Fork() can be used on a thread to make children threads, and their timing is scheduled by the kernel.

It is faster the switch threads then it is to switch processes

123
Q

5: What are the components of a thread?

A

Each thread has the following:

  • A unique thread ID
  • Memory in Stack segment (function call stack)
  • Program counter, counting program instructions

All threads share:

  • Address space of processes
  • Memory in Data segment
  • Memory in Code segment
124
Q

7: What is scope? What are different variable scopes?

A

block scope: variable declared and used within a block

file scope: variable is defined outside of any block and can be used anywhere in the file

function prototype scope: parameters for functions only exist when the function is running

function scope: defined in a function block

125
Q

7: What content usually goes in a header file?

A
  • no code
  • global constant declarations
  • global type definitions
  • forward declarations of function prototypes
126
Q

7: What is a library?

A
  • a set of commonly used functions that are reusable and can be used by many different programs
  • not executable
  • has .h and .a files
127
Q

5: How is a thread created?

A

Steps to create a thread:

  1. # include pthread.h
  2. pthread_create(address, attri=NULL, fnc*, fncParam)
  3. pthread_exit(void *status)
  4. pthread_join(pthread_t thread, void *status)
  5. gcc with -lpthread at end
128
Q

5: How are semaphores used to stop improper context switching in a thread?

A

The semaphore is used as a counter with 0 and non-0 values to indicate use of resource. Create by:

#include semaphore.h
sem_t semaphore;
sem_init (&amp;semaphore, use  b/ threads = 0, inti val = 1)
sem_wait(&amp;semaphore); - Fnc waits on semaphore, if free semaphore value is decreased
sem_post(&amp;semaphore); - Fnc to release lock
129
Q

5: How are mutexs used to stop improper context switching in a thread?

A

The mutex is used with a binary 1 or 0 value. If 1 = resource free, if 0 = resource used.

130
Q

8: What are the steps for creating a simple window in X11? Then what are the steps for removing it?

A
  1. Connect to server

Display *display;
display = XOpenDisplay(NULL);

  1. Make the window

Window *window;
window = XCreateSimpleWindow({display}{parent}{x}{y}{width}{height}{borderwidth}{bordercolour}{background colour});

display is what is returned from step 1

Where x and y are the position of the top left corner of the window

parent is RootWindow({display},0);

  1. Make the window visible by mapping it to the display

XMapWindow({display},{window})

  1. Ensure that it has been displayed

XFlush({display})

TO REMOVE:

XUnmapWindow(display, window)
XDestroyWindow(display,window)
XCloseDisplay(display);

131
Q

8: How do you handle a window closing event correctly?

A

Tell the window
manager that we are interested in window deletion events by calling XSetWMProtocols() and
registering a WM_DELETE_WINDOW message with it. Then we’ll get a client message from the
window manager when the user tries to close the window.

We add this code any time after
making the window:

Atom WM_DELETE_WINDOW = XInternAtom(display, “WM_DELETE_WINDOW”, False);

XSetWMProtocols(display, win, &WM_DELETE_WINDOW, 1);

132
Q

8: How do you register a screen event and handle it?

A

Enter an infinite while loop, getting an event and handling it:

XEvent event;
while(1) {
 XNextEvent(display, &amp;event);
 switch(event.type) {
 case ButtonPress:
 …
 break;
 case ButtonRelease:
 …
 break;
 case ConfigureNotify:
 …
 break;
 //... etc ...
 }
}
133
Q

8: How can you loop code in order to draw a object moving across a screen?

A

while(1) {
XSetForeground(display, gc, 0xFFFFFF);
XFillRectangle(display, win, gc, 0, 0, WIN_SIZE, WIN_SIZE/2);

drawCar(x, y);

if (x+100 < WIN_SIZE)
x += 10;

XFlush(display);
usleep(100000);
}

134
Q

8: How do you create a graphics context with X11?

A

GC = XCreateGC({display},{window},{value_mask ==0},{values ==NULL});

use the GC to start drawing with other functions such as:

XDrawPoint(display, window, GC, x, y);

135
Q

8: What is the golden angle?

A

137.51 degrees

It is found in nature and is the ideal angle for producing spirals as in seashells, flower petals and etc.

It is ideal as it minimizes overlap during multiple rounds of spiralling