XXXXXXXXXXlabs/lab5.md at master · ITF22519/labs https://github.com/ITF22519/labs/blob/master/lab5/lab5.md 1/8 ITF22519 / labs Private Code Issues Pull requests Actions Projects Security Insights labs...

1 answer below »
There are some extra files for those, but i cannot see them being refered to in the labs. Please let me know if they are. Need 250 points


1.10.2020 labs/lab5.md at master · ITF22519/labs https://github.com/ITF22519/labs/blob/master/lab5/lab5.md 1/8 ITF22519 / labs Private Code Issues Pull requests Actions Projects Security Insights labs / lab5 / lab5.md anlam Update lab5.md Latest commit 428f5cf 13 days ago History 1 contributor Learn Git and GitHub without any code! Using the Hello World guide, you’ll start a branch, write comments, and open a pull request. Read the guide master Go to file 298 lines (234 sloc) 13.2 KB ITF22519 - Introduction to Operating Systems Autumn 2020 Lab 5: Introduction to Unix Processes Before you start, remember to commit and push your previous lab to your git repository. Then, try to pull the new lab: $ cd ITF22519/labs $ git pull upstream master $ git pull origin master $ cd lab5 Please remember these steps for the future labs. Raw Blame https://github.com/ITF22519 https://github.com/ITF22519/labs https://github.com/ITF22519/labs https://github.com/ITF22519/labs/issues https://github.com/ITF22519/labs/pulls https://github.com/ITF22519/labs/actions https://github.com/ITF22519/labs/projects https://github.com/ITF22519/labs/security https://github.com/ITF22519/labs/network/dependencies https://github.com/ITF22519/labs https://github.com/ITF22519/labs/tree/master/lab5 https://github.com/anlam https://github.com/anlam https://github.com/ITF22519/labs/commit/428f5cfa19c8ce3f50025c0e13408b76c5fa1230 https://github.com/ITF22519/labs/commit/428f5cfa19c8ce3f50025c0e13408b76c5fa1230 https://github.com/ITF22519/labs/commits/master/lab5/lab5.md https://guides.github.com/activities/hello-world/ https://github.com/ITF22519/labs/find/master https://github.com/ITF22519/labs/raw/master/lab5/lab5.md https://github.com/ITF22519/labs/blame/master/lab5/lab5.md x-github-client://openRepo/https://github.com/ITF22519/labs?branch=master&filepath=lab5%2Flab5.md https://github.com/login?return_to=%2FITF22519%2Flabs%2Fblob%2Fmaster%2Flab5%2Flab5.md https://github.com/login?return_to=%2FITF22519%2Flabs%2Fblob%2Fmaster%2Flab5%2Flab5.md 1.10.2020 labs/lab5.md at master · ITF22519/labs https://github.com/ITF22519/labs/blob/master/lab5/lab5.md 2/8 I wrote this lab using Markdown ( .md ) which is a very simple markup language for documentation. You can find an example of markdown here. I was thinking maybe you should also try using markdown to write your reports (or enter your answers of the lab exercises directly into this file). This is not mandatory, just a suggestion. I just wanted to introduce to you a very cool language that developers use to document their code. About Unix Processes 1. When a system is booted, the first user space process is systemd (or /sbin/init depending on your Linux Distribution), and has a PID of 1. This process will in turn launch startup scripts and eventually login prompts. If you do a ps -el , you should see that process 1 is systemd . It will be the ancestor of all other user processes on the system. 2. When you login or start a terminal, a process for the shell is started. The shell will then launch other processes, which will be children of the shell. If the parent process dies (for example, you exit the shell), systemd will adopt the orphaned processes (on Linux and many other Unix variants). 3. The status of a Unix process is shown as the second column of the process table (viewed by executing the ps command). Some of the states are R: running, S: sleeping, Z: zombie. Process Table The program print_pid.c prints out its process id as well as its parent’s id, and then sleeps for 2 minutes. Run the program print_pid.c twice, both times as a background process (i.e. suffix it with an ampersand “ & ”): $ ./print_pid & Ctrl+C $ ./print_pid & Ctrl+C Pay attention to the id of the parent processes printed by this program. Once both processes are running as background processes, view the process table (use ps -l to view only the processes running on your terminal, or ps -el to view all processes on the system). If you see the message “I am awake”, the process has finished and will no longer show up in the process table. The first line from a ps -l is duplicated here: F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD A short description of the fields could be found here: https://docs.oracle.com/cd/E19455-01/805-7229/spprocess-47/index.html. You should be able to find more details of these fields in the ps manual page ( man ps ). Exercise 1 (10 pts) (8 pts) In the report, include only relevant lines from ps -l for your programs, and point out the following items: process name (Process CMD) process state (decode the letter!) process ID (PID) parent process ID (PPID) (2 pts) Find out the name of the process that started your print_pid programs. What is it, and what does it do? https://github.com/ITF22519/demo-markdown https://docs.oracle.com/cd/E19455-01/805-7229/spprocess-47/index.html 1.10.2020 labs/lab5.md at master · ITF22519/labs https://github.com/ITF22519/labs/blob/master/lab5/lab5.md 3/8 Kill processes Now that you know how to find a PID for a running program, you can use kill to terminate an unwanted process. Just type kill followed by the process ID. If a process refuses to terminate, kill -9 followed by the process ID will terminate any process you have permission to kill. You might also try killall to kill all processes with the same name (try man killall for more information). $ killall print_pid The fork() system call The fork() call creates a child that is a copy of the parent process. Because the child is a copy, both it and its parent process begin from just after the fork() . All of the statements after a call to fork() are executed by both the parent and child processes. However, both processes are now separate and changes in one do not affect the other. The code fragment below calls fork() once, which results in the creation of one child process. Then, each process prints out its id and the parent’s id. int main() { fork(); printf("Process %d's parent process ID is %d\n", getpid(), getppid()); return 0; } The output of this program could be: Process 14427's parent process ID is 6891 Process 14428's parent process ID is 14427 Here, the id of the main function is 14427, the child id is 14428, and the id of bash shell is 6891. The process tree of this program is showed below. Exercise 2 (10 pts) Compile and execute the program fork_ex1.c . https://github.com/ITF22519/labs/blob/master/lab5/img/process_tree.png 1.10.2020 labs/lab5.md at master · ITF22519/labs https://github.com/ITF22519/labs/blob/master/lab5/lab5.md 4/8 (1 pts) Include the output of the program. (5 pts) Draw the process tree (label processes with PIDs). (4 pts) Explain how the tree was built. Make the new Process do Something Different Since the fork() function call creates a clone of the parent process and returns different values for the parent and child processes. Using these two return values, the child process can be made to do something that is not the same as the parent. Firstly, we can use the fact that the value returned by fork() is zero for the child. To differentiate between which process is which, the simplest is to use an if statement. Exercise 3 (5 pts) The program fork_ex2.c prints different messages in the child and parent processes. Complete the condition of the if statements in this program. Waiting on the Child Process When running the program fork_ex2.c , the parent and child process will each execute at their own pace, and either can finish execution before the other. In the event that this is not the desired behavior, there are two system calls that the parent can run that will guarantee that the parent waits for the child process to exit. The two functions are wait() and waitpid() . Full information on what each of these functions do and how they are used can be found at the manual page: $ man 2 wait To use wait() to make the parent process wait for the child process to complete, the following snippet of code is used: #include #include ... int status = 0; ... child = fork(); if(child == 0) { //does something cool } else if(child > 0) { wait(&status); printf("child process is done, status is: %d\n", status); return 0; } else { perror("fork"); exit(-1); } 1.10.2020 labs/lab5.md at master · ITF22519/labs https://github.com/ITF22519/labs/blob/master/lab5/lab5.md 5/8 This snippet will make sure that the parent suspends execution until one of its children terminates. In the event that there are multiple children, and knowledge of a specific child process’ termination is of importance, then waitpid() should be used to tell the parent process to wait. The code snippet to do that is: #include #include ... int status = 0; ... child = fork(); if(child == 0) { //does something cool } else if(child > 0) { waitpid(child, &status, 0); printf("child process is done, status is: %d\n", status); return 0; } else { perror("fork"); exit(-1); } This will guarantee that the parent process wait for the child process with the process id stored in child to terminate before continuing. Note that, as shown in the man pages for wait() , to make this snippet of code work like the previous snippet, change the value of the first argument for waitpid() (the argument that is occupied by the variable child ) to -1 and the behavior of this snippet and the previous snippet would be the same. So effectively: wait(&status); // is the same as waitpid(-1, &status, 0); The call to the wait() function results in a number of actions: If the calling process has no children, wait() returns -1 . If the calling process has a child that has terminated (a zombie), that child’s PID is returned and it is removed from the process table. Otherwise, the call blocks (suspends the process) until a child terminates. The waitpid() function allows the WNOHANG flag to be specified to return immediately in all cases. It is highly recommended that the student read through the man page for wait() and waitpid() to fully understand how to use wait() and waitpid() and experiment with multiple fork() and wait() programs until fully comfortable with what is actually happening. What is presented here is merely a quick overview of how to use the two. Exercise 4 (5 pts) Summarize the usage of wait() and waitpid() . Making a Process Run Another
Answered Same DayOct 01, 2021

Answer To: XXXXXXXXXXlabs/lab5.md at master · ITF22519/labs...

Shivani answered on Oct 04 2021
148 Votes
Solution/lab4/Array.txt
10
12
14
65
32
12
46
53
15
67
23
Solution/lab4/lab4_ex1.c
/*Lab4: Exercise 1
Write a program that (1) gets a character from user input (2) gets a string from user input
and (3) calculates the number of input character in the input string. */
#include
#include
int main()
{
    char ch;
    char str[100];
    int count=0;
    
    printf("Enter a character: ");
    ch=getchar();
    fflush(stdin);
    
printf("Enter a string: ");
gets(str);
int i=0;
    while(*(str+i) != '\0')
    {
if (*(str+i) == ch)
            count++;
        i++;
    }

    printf("The number of input character in the string is: %d", count);
return 0;
}
Solution/lab4/lab4_ex2.c
/* Lab-4: Ex2
Use pointers to write a program that gets integers from a user, puts the integers in an array,
and prints out the integers in reverse order. */
#include
#include
int main()
{
    int n; // number of elements in the array
    int *A; // Array
    int itr;
    
    printf("\nEnter the size of array:");
    sc
anf("%d", &n);
    fflush(stdin);
                                        
    A = malloc(n*sizeof(int)); // memory allocation
    A = (int*)malloc(n*sizeof(int));
    if (A== NULL)
    {
        printf("Error in Memory Allocation");
        exit (0);
    }
    
    printf("Input values for the array: ");
    for(itr=0; itr    {
        scanf("%d",(A+itr));
    }
    
    printf("\nThe input array is:");
    for(itr=0;itr        printf(" %d",*(A+itr));
    printf("\nArray printed in reverse order: ");
    for(itr=n-1;itr>=0;itr--)
        printf(" %d",*(A+itr));
    
    free(A);
    
    return 0;
}
Solution/lab4/lab4_ex3.c
/* Lab4: Ex3:
Write a program that (a) reads the first element of Array.txt and assigns it to a variable
n, (b) creates an array A with the size n and dynamically allocates memory for A, (c) reads
the next n elements of Array.txt and assigns these elements with the corresponding elements
in array A - if there are not enough n valid elements in Array.txt, print out error message,
(d) prints array A and (e) finds the maximum element of A */
#include
#include
int main()
{
FILE *fp;
int *A;
int n, i;
fp = fopen("Array.txt", "r");
if(NULL == fp)
{
printf("Unable to open file\n");
exit(-1);
}
    
    // reading the first line of the file
    fscanf(fp, "%d", &n);
    
    // Allocating memory to the array
    A = malloc(n*sizeof(int));
    printf("Number of elements in the array: %d",n);
    
    // reading numbers from the file into the array
    for(i=0;i    {
        if(fscanf(fp, "%d", (A+i)) == EOF)
        {
            printf("\nERROR: File do not contain enough numbers.");
            exit(-1);
        }
    }
            
    // Printing the array elements
    printf("\nArray is: ");
    for(i=0;i            printf("%d ", *(A+i));    
    
    // Finding the maximum element of the array
    int max=0;
    for(i=0;i    {
        if(*(A+i) > max)
            max = *(A+i);
    }
    printf("\nMaximum element of the array: %d", max);
    
fclose(fp); //Close the file pointer
return 0;
}
Solution/lab4/lab4_task1.c
/* Lab-4: Task-1: Calculate the number of a character in a string */
#include
int main()
{
    char s[] = "This Is The Operating System Course";
    char ch = 'e';
    int count = 0; // store the number of e in string s
    
    int itr=0; // iterator to iterate through the string
    while(s[itr] != 0)
    {
        if(s[itr] == ch)
        {
            count++;
        }
        itr++;
    }
    printf("The character %c appears %d times\n", ch, count);
    return 0;
}
Solution/lab4/lab4_task2.c
/* Lab-4: Task-2: Arithmetic Operators Using Pointer */
#include
int main()
{
    int num1, num2;
    int *p1, *p2;
    int sum, diff, mul, div;
    
    printf("\nEnter one integer: ");
    scanf("%d", &num1);
    fflush(stdin);
    
    printf("Enter another integer: ");
    scanf("%d", &num2);
    fflush(stdin);
    
    /* assigning to pointers*/
    p1 = &num1;
    p2 = &num2;
    
    printf("\nThe first integer is stored at the address: %p", p1);
    printf("\nThe second integer is stored at the address: %p", p2);
    
    sum = *p1 + *p2;
    diff = *p1 - *p2;
    mul = *p1 * *p2;
    div = *p1 / *p2;
    
    printf("\nSummation: %d", sum);
    printf("\nDifference: %d", diff);
    printf("\nMultiplication: %d", mul);
    printf("\nDivision: %d", div);    
}
Solution/lab4/lab4_task3.c
/* Lab-4: Task-3: Fixing bugs */
#include
void change(int *ptr1, int *ptr2)
{
    int temp;
    
    temp = *ptr1;
    *ptr1 = *ptr2;
    *ptr2 = temp;
}
int main()
{
    int num1, num2;
    
    printf("\nEnter the first number: ");
    scanf("%d", &num1);
    printf("\nEnter the second number: ");
    scanf("%d", &num2);
    
    change(&num1, &num2);
    
    printf("\n\nAfter changing two numbers:");
    printf("\nThe first number is: %d", num1);
    printf("\nThe second number is: %d\n", num2);
    
    return 0;
}
Solution/lab4/lab4_task4.c
/* Lab-4: Task-4: program that prints out the number of characters in a string */
#include
int calStringLength(char *tmpStr);
int main()
{
    char str[20];
    int length;
    
    printf("Enter a string you want to count: ");
    gets(str);
    
    length = calStringLength(str);
    printf("Its length is: %d", length);
}
int calStringLength(char *tmpStr)
{
    int count = 0;
    
    while (*tmpStr != '\0')
    {
        count++;
        tmpStr++;
    }
    
    return(count);
}
Solution/lab4/lab4_task5.c
/* Lab-4: Task-5: **
* code to read the content of file Array.txt which includes 10 integers and put
these integers into an array A. Write your code to (a) print each element of A on the
terminal, (b) calculate the summation of all elements in A, and (c) print the summation on
the terminal. **/
#include
#include
int main()
{
FILE *fp;
int *A;
int n=10, i;
fp = fopen("Array.txt", "r");
if(NULL == fp)
{
printf("Unable to open file\n");
exit(-1);
}
    
    // Allocating memory to the array
    A = malloc(10*sizeof(int));
    
    // reading numbers from the file into the array
    for(i=0;i        fscanf(fp, "%d", (A+i));
            
    // Printing the array elements
    printf("\nArray is: ");
    for(i=0;i            printf("%d ", *(A+i));    
    
    // Finding the maximum element of the array
    int sum=0;
    for(i=0;i        sum += *(A+i);
        
    printf("\nSum of elements of the array: %d", sum);
    
fclose(fp); //Close the file pointer
return 0;
}
Solution/lab4/lab4_task6.c
/* Lab-4: Task-6: Dynamic memory allocation with an array */
#include
#include
int main()
{
    int n; // number of elements in the array
    int *A; // Array
    int itr;
    
    // YOUR code to get array size, put it in variable n
    printf("\nNumber of elements in the array:");
    scanf("%d", &n);
    fflush(stdin);
    // End of array size
                                        
    A = malloc(n*sizeof(int)); // memory allocation
    
    // MY code for memory allocation
    A = (int*)malloc(n*sizeof(int));
    if (A== NULL)
    {
        printf("Error in Memory Allocation");
        exit (0);
    }
    // END of my code
    
    // YOUR code to fill out elements of the array
    printf("Enter array elements: ");
    for(itr=0; itr    {
        scanf("%d",(A+itr));
    }
    
    // YOUR code to print the array
    printf("\nArray:");
    for(itr=0;itr        printf(" %d",*(A+itr));
    
    // Your code for memory deallocation
    free(A);
    // DONE!
    return 0;
}
Solution/lab4/lab4_task7.c
/* Lab4: Task7: Dynamic memory allocation with two dimensional array*/
#include
#include
int main()
{
    int m, n;
    
    printf("Enter the nmuber of rows and columns for matrix: ");
    scanf("%d%d", &m, &n);
    
    int **a;
    
    //Allocate memory to matrix
    a = (int **) malloc(m * sizeof(int *));
    
    for(int i=0; i    {
        a[i] = (int *) malloc(n * sizeof(int));    
    }
    
    //YOUR CODE HERE
    // Fill-out matrix from a user input
    printf("Enter matrix elements:");
    for(int i=0;i    {
        for(int j=0;j            scanf("%d", (a+ i*n +j));
    }
    // Matrix printing.
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
            printf("%d ", *(a + i*n + j));
        printf("\n");
    }
    
    // Memory deallocation
    free(a);
    // END OF YOUR CODE
    return 0;
}
Solution/lab5/cal.c
#include
#include
#include
#include
#include
#include
void main (int argc, char *argv[])
{
if(argc < 4)
{
printf("usage: cal \n");
exit(0);
}

int num1 = atoi(argv[2]);
int num2 = atoi(argv[3]);
int result = 0;

if(strcmp(argv[1], "add") == 0)
{
result = num1 + num2;
}
else if(strcmp(argv[1], "sub") == 0)
{
result = num1 - num2;
}
else if(strcmp(argv[1], "mul") == 0)
{
result = num1 * num2;
}
else if(strcmp(argv[1], "div") == 0)
{
result = num1/num2;
}
else
{
printf("Unknown Operator: %s\n", argv[1]);
exit(0);
}

printf("%d %s %d equals %d\n", num1, argv[1], num2, result);
}
Solution/lab5/exe1.c
#include
#include
int main()
{
    execl("/bin/ls", "ls", NULL);
    printf("What happened?\n");
}
Solution/lab5/exec_cal.c
/* exec_cal.c : This program reads input from the user for
the operator (add, mul, div, sub), num1 and num2. Then it creates a new child process, and executes the cal program with the collected
arguments from the user. */
#include
#include
#include
#include
#include
#include
int main(int argc, char* argv[])
{
    pid_t pid;
    char op[10];
    int num1, num2;
    int return_status;
    
    printf("Enter the operator (add, sub, mul, div)\n");
    if(scanf("%s", op) != 1)
    {
        printf("Cannot read operator");
        exit(-1);
    }
    
    //TODO: check if operator is correct (add, sub, mul, div).
    //Otherwise, print an error message and exit
    //Hint: check return value of scanf
    if((strcmp(op,"add") != 0) && (strcmp(op,"sub") != 0) && (strcmp(op,"mul") != 0) && (strcmp(op,"div") != 0))
    {
        printf("Invalid Operator. Try again with a correct operator (add, sub, mul, div\n");
        exit(-1);
    }
    
    printf("Enter the first number\n");
    //TODO: Read an integer from user input and store inside num1.
    //On eror, print an error message and exit.
    if(scanf("%d", &num1) != 1)
    {
        printf("Cannot read operator");
        exit(-1);
    }    
    printf("Enter the second number\n");
    //TODO: Read an integer from user input and store inside num2.
//On eror, print an...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here