Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First commit: class and video notes only #378

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
230 changes: 230 additions & 0 deletions NOTES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
# Processes

## Requirements to Execute a Program
- CPU number of cores
- Memory

### Example of an Address Space (P1 RAM between P2 RAM and P3 RAM)

low address |
_______________________________________________________________________|
high address Command-line Args & Environment Variable |
|
stack Static Memory |
|
int main |
func1 |
func2 | |
|
heap Dynamically-allocated memory malloc data |
|
|
uninitialized data (bss) initialized to zero by exec |
|
initialized data \ |
} read from program file by exec |
text / |
|
low address |
_______________________________________________________________________|
high address |
|


Processes are isolated by default (unaware of each other by default)

## Initializing a Process

- Allocation of working memory.
- Entry is added to the operating system's processing list.
- OS's scheduling algorithm schedules the newly-initialized process.

## Scheduling
Process List
PID Command
1 a
2 b
3 c -->
4 d Context CPU
5 e Switching
6 f <--
7 g
8 h

PID (Process Identifier Number): 2 byte number

## Privileged vs. Non-Privileged
Privileged operations
- Creating new processes
- destroying existing processes
- Allocating memory
- Accessing hardware functionality
- scheduling algorithm

Non-Privileged operations
- everything I write. :)


# System Calls
- A request to the OS to perform a privileged operation on its behalf.
- Uses requests and response (similar to API calls)

System calls with requests and responses is:
- Less Performant but Safer

MS-DOS allowed Processes to perform a privileged operations, which is why games are more prevelant on Windows than Mac.

Request
--------> ---------->
Processes OS (Gatekeeper) Hardware
<-------- <---------
Response

- Most languages rely on C to do the actual requests and responses.

Example of Request System Call:
- malloc()
- fork()



P1 P2
x (executed) x (value carried over)
y (executed) y (value carried over)
z (executed) z (value carried over)
fork() => creates a forked copy fork () (carried over)

Parent code Child Code


if P2 also executes the fork it is a problem referred to as a fork bomb.

## Commonly-Used System Calls
- fork() create copy of existing process
- exec() execute a specified file
- chdir() change working directory
- pipe() creates a way for interprocess communication.

fork()
- creates a child process, which is a copy from the parent process
- returns twice:
- one result in the parent
- another result in the child

pipe()
- uni-directional: one write end & one read end;
- initalize pipe first then fork

P1 P2
| | | |
| |_____| |
w -> _____ -> r
| | | |
| | | |
| |_____| |
r <- _____ <- w |
| | | |
| | | |









```c
# include
// putchar: writes a character to the standard output (stdout);
// it is equivalent to calling putc iwth stdout as second argument.
void print_str(char *s) {
int i;
char *p = s; // saving a copy of s
// putchar(** take a character argument)
//iterate over s and use putchar for every character on the array of characters.
for(i = 0; s[i] != '\0; i++) {
putchar(s[i]);
}

// equivalent method
for(i = 0; *(s+i) != '\0; i++) {
putchar(*s(i+i));
}

// another method: it manipulates the values themselves
for(; *s != '\0; s++) {
putchar(*s);
}

// after doing the last method (the s pointer is pointing to '\0' so calling the first method will no longer work since s is already at '\0'). So we need to add:
s = p;

while (*s != '\0') {
putchar(*(s++))
/* combines 2 lines of into one; it is equivalent to:
putchar(*s);
s++;
*/
}


}
int main(void) {
pid_t pid;
pid = fork(); // doesn't take paramters
if (pid == 0) {
printf("I am the child\n");
} else {
printf("Parent is about to wait\n");
wait(NULL) // if this is commentted result will be different.
printf("I am the parent\n");
}


return 0;
}
```

```c
# include
// putchar: writes a character to the standard output (stdout);
// it is equivalent to calling putc with stdout as second argument.


/*
size_t write(int fd, void* buf, size_t cnt);
fd: file descripter: a pointer to a file
buf: buffer to write data to
cnt: length of buffer

size_t is typedef howevers it's going to return how many bytes were actually written

return Number of bytes written on success
return 0 on reaching end of file
return -1 on error
*/


void putchar_ls(char c) {
// c is a vlue we need to have a pointer
//so we use & to point to the address of c
write(1, &c, 1);
// sz = write(1, &c, 1);
// printf("\n%d\n", sz);
}

void print_str(char *s) {
while(*s != '\0') {
putchar_ls(*(s++))
}
}


}
int main(void) {

printf("HelloWorld\n");
return 0;
}

Binary file added SchedulingDiagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions ShellDemo.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


#define MAX_COMMANDLINE_LEN 8192 // constant variable in global scope
#define MAX_COMMANDLINE_ARGS 128 // constant variable in global scope

/* PROTOTYPE */
void parse_commandline(char *commandline, char *exec_commands[], int max_count);
// pointers





int main(void) {
char commandline[MAX_COMMANDLINE_LEN];
// char **exec_commands
char *exec_commands[MAX_COMMANDLINE_ARGS]
return 0;
}
Binary file added ShellDemoSean
Binary file not shown.
112 changes: 112 additions & 0 deletions ShellDemoSean.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>

#define MAX_TOKENS 100

char **parse_commandline(char *str, int *argc, char **args)
{
char *token;
*argc = 0;

// Break the given str down into tokens using a delimiter
// More specifically, we'll split on tabs, newlines, and carriage returns
token = strtok(str, " \t\n\r");

// Add this token to the args array
while (token != NULL && *argc < MAX_TOKENS) {
// Index into args array using the value in argc
// Then increment *argc
args[(*argc)++] = token;

// Fetch the next token
token = strtok(NULL, " \t\n\r");
}

// Lastly, add a NULL as the last element in args
args[*argc] = NULL;

return args;
}

int main(void)
{
// Holds the entire command line input all at once
char commandline[1024];
// Holds individual parsed tokens
char *args[MAX_TOKENS];
// Number of args stored in the args array
int argc;

// In a continuous loop
while (1) {
// Receive input from stdin
// shell should print a prompt for the user
printf("lambda-shell$");

// Read input from stdin
fgets(commandline, sizeof(commandline), stdin);

// Parse that input into tokens
// Parse the commandline buffer into individual args
parse_commandline(commandline, &argc, args);

// Check for some specific commands
// Like an exit command or other such commands
if (argc == 0) {
continue;
}

// Check for an "exit" command
if (argc == 1 && strcmp(args[0], "exit") == 0) {
break;
}

// Check for "cd" command
if (strcmp(args[0], "cd") == 0) {
if (argc != 2) {
printf("usage: cd dirname\n");
continue;
}

// Change to the specified directory
if (chdir(args[1]) < 0) {
fprintf(stderr, "chdir failed");
continue;
}

// If we successfully changed directories, continue our shell loop
continue;
}

// To allow us to execute arbitrary programs,
// use fork and exec in concert
// Fork this process
// In the child context, exec with the specified program name

pid_t child_pid = fork();

if (child_pid < 0) {
fprintf(stderr, "fork failed");
continue;
}

// In the child context
if (child_pid == 0) {
// Exec the child program, transforming it in the specified command
execvp(args[0], args);

// If we get here, that means the exec call failed
fprintf(stderr, "exec failed");
exit(1);
} else {
// In the parent context
// Wait for the child to complete
waitpid(child_pid, NULL, 0);
}
}

return 0;
}
Binary file added ex1/ex1
Binary file not shown.
Loading