SlideShare a Scribd company logo
1 of 15
cmdfile.txt
sleep 5
ls -latr
sleep 3
pwd
sleep 1
wc /etc/passwd
CommandNode.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "CommandNode.h"
/**
*CommandNode.c
*The function bodies for a linked list of commands
**/
/**
Example of linked list initialization in code:
//First command node (head of list)
headCommand =
(CommandNode*)malloc(sizeof(CommandNode));
CreateCommandNode(headCommand, command, index,
NULL);
index = 1;
.....
//Later command nodes
while ((linesize = getline(&line, &len, fp)) >= 0) {
...
index++;
nextCommand1 =
(CommandNode*)malloc(sizeof(CommandNode));
CreateCommandNode(nextCommand1, command, index,
NULL);
InsertCommandAfter(headCommand, nextCommand1);
}
**/
//create a new command node. usually nextCmd can be NULL
and function InsertCommandAfter can be called to insert after
head node.
void CreateCommandNode(CommandNode* thisNode, char
cmd[20][20], int ind, CommandNode* nextCmd) {
//this is useful if you store a string (char *): strcpy(thisNode-
>command, cmd);
for (int i = 0; i < 20; i++)
for (int j = 0; j < 20; j++)
thisNode->command[i][j] = cmd[i][j];
thisNode->index = ind;
thisNode->nextCommandPtr = nextCmd;
return;
}
//insert node newNode after thisNode
void InsertCommandAfter(CommandNode* thisNode,
CommandNode* newNode) {
CommandNode* tmpNext = NULL;
tmpNext = thisNode->nextCommandPtr;
thisNode->nextCommandPtr = newNode;
newNode->nextCommandPtr = tmpNext;
return;
}
//get next command node in linked list
CommandNode* GetNextCommand(CommandNode* thisNode)
{
return thisNode->nextCommandPtr;
}
//find a command based on the pid
CommandNode* FindCommand(CommandNode* cmd, int pid) {
CommandNode* tmpNext = cmd;
while (tmpNext != NULL) {
if (tmpNext->PID == pid) { return tmpNext; }
tmpNext = tmpNext->nextCommandPtr;
}
return NULL;
}
CommandNode.h
/**
*CommandNode.h
*The struct for a Command Node and function prototypes for a
linked list of commands
**/
typedef struct command_struct {
char command[20][20];
int index;
int PID;
int starttime;
struct command_struct* nextCommandPtr;
} CommandNode;
void CreateCommandNode(CommandNode* thisNode, char
cmd[20][20], int ind, CommandNode* nextCmd);
void InsertCommandAfter(CommandNode* thisNode,
CommandNode* newNode);
CommandNode* GetNextCommand(CommandNode* thisNode);
CommandNode* FindCommand(CommandNode* cmd, int pid);
HWdetails&helperFile/HW_details1.jpg
HWdetails&helperFile/HW_details1_1.jpg
HWdetails&helperFile/read_parse_file.c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
char newString[20][20];
int i,j,ctr;
fp = fopen("commands.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
printf("---------------------------------------n");
printf("nn Split string by space into words :n");
printf("Retrieved line of length %zu:n", read);
printf("%s", line);
for (int i=0; i<20; i++)
for (int j=0; j<20; j++)
newString[i][j]=0;
j=0; ctr=0;
for(i=0;i<=(strlen(line));i++)
{
// if space or NULL found, assign NULL into
newString[ctr]
if(line[i]==' '||line[i]=='0')
{
newString[ctr][j]='0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=line[i];
j++;
}
}
printf("n Strings or words after split by space are :n");
for(i=0;i < ctr;i++)
printf(" %sn",newString[i]);
}
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
HWdetails&helperFile/SampleOutput.jpg
HWdetails&helperFile/shell1_execvp.c
#include "apue.h"
#include <sys/wait.h>
int
main(void)
{
pid_tpid;
int status;
char buf[1][5];
char *buf2[6];
buf[0][0] = '.';
buf[0][1] = '.';
buf[0][2] = 0;
buf2[0] = "ls";
buf2[1] = "-latr";
buf2[2] = "/etc/passwd";
buf2[3] = (char *)&buf[0][0];
buf2[4] = (char *)0;
buf2[5] = (char *)0;
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* child */
execvp(buf2[0], buf2);
err_ret("couldn't execute: %s", buf2[0]);
exit(127);
}
/* parent */
if ((pid = waitpid(pid, &status, 0)) < 0)
err_sys("waitpid error");
printf("DONE ");
exit(0);
}
HWdetails&helperFile/skeleton_solution.c
//---------------------------
//fork the commands and record the start times
CommandNode *headNode; /** This is the beginning of your
linked list of CommandNodes **/
....
CommandNode *tmpNode;
tmpNode = headNode;
while (tmpNode != NULL) {
//save the startime!
// tmpNode.starttime = starttime
pid = fork();
if (pid < 0) {
fprintf(stderr, "error forking");
exit(2);
} else if (pid == 0) { /*child */
//See shell1_execvp.c for execvp usage
execvp(....tmpNode.command); /*executes the command in
the specific node */
} else if (pid > 0) { /* parent goes to the next node */
tmpNode.pid = pid;
int fdout = open("%d.out", tmpNode.index);
int fderr = open("%d.err", tmpNode.index);
fprintf(fdout, "Starting command INDEX %d: child PID
%d of parent PPID %d.n", tmpNode.index, pid, getpid() );
tmpNode = tmpNode->nextCommandPtr;
}
} /*end of while loop */
//---------------------------
//Final while loop: waits until anything has completed,
//this will exit (wait returns -1)
//when there is no more child process. Then your parent process
exits.
while((pid = wait(&status)) >= 0) {
if(pid > 0) {
//finishtime = get the finish time
//search your linked list for the node that corresponds to
pid
//The function FindNode was provided
//node=FindNode(pid)
//signal handling
int fdout = open("%d.out", node.index);
int fderr = open("%d.err", node.index);
fprintf(stderr, "Process with PID %d terminated.n", pid);
if (WIFEXITED(status)) {
fprintf(fderr, "Child %d terminated normally with exit
code: %dn",
pid, WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
fprintf(fderr, "Child %d terminated abnormally with
signal number: %dn",
pid, WTERMSIG(status)); }
//
//to compute the elapsed time you subtract
//elapsedtime = finishtime - node.start_time
//decide if you will restart
//if (elapsedtime > 2) {
//record the new starttime
// node.starttime = new starttime
// pid = fork();
// if (pid < 0) //error
// else if (pid == 0) { //child
//See shell1_execvp.c for execvp usage
// execvp(node.cmd);
// } else if (pid > 0) {
// node.pid = pid;
// }
}
}
time_demo.c
/* Program to demonstrate time taken by function fun() */
#include <stdio.h>
#include <time.h>
// A function that terminates when enter key is pressed
void fun()
{
printf("fun() starts n");
printf("Press enter to stop fun n");
while(1)
{
if (getchar())
break;
}
printf("fun() ends n");
}
// The main program calls fun() and measures time taken by
fun()
int main()
{
// Calculate the time taken by fun()
struct timespec start, finish;
double elapsed;
clock_t t;
t = clock();
clock_gettime(CLOCK_MONOTONIC, &start);
printf("start %ldn", start.tv_sec);
fun();
clock_gettime(CLOCK_MONOTONIC, &finish);
printf("finish %ldn", finish.tv_sec);
//printf("CLOCKSPERSEC %ldn", CLOCKS_PER_SEC);
//double time_taken =
((double)t)*1000.0/CLOCKS_PER_SEC; // in seconds
elapsed = (finish.tv_sec - start.tv_sec);
//Alternative with more precision:
//elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
printf("fun() took %f seconds to execute n", elapsed);
return 0;
}

More Related Content

Similar to cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx

4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statementsMomenMostafa
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxhappycocoman
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Yandex
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020vrgokila
 
sodapdf-converted into ppt presentation(1).pdf
sodapdf-converted into ppt presentation(1).pdfsodapdf-converted into ppt presentation(1).pdf
sodapdf-converted into ppt presentation(1).pdfMuhammadMaazShaik
 
Write a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfWrite a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfjillisacebi75827
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using CBilal Mirza
 
#include stdio.h#include stdlib.h#include string.h#inclu.pdf
#include stdio.h#include stdlib.h#include string.h#inclu.pdf#include stdio.h#include stdlib.h#include string.h#inclu.pdf
#include stdio.h#include stdlib.h#include string.h#inclu.pdfapleather
 
Computer Networks Lab File
Computer Networks Lab FileComputer Networks Lab File
Computer Networks Lab FileKandarp Tiwari
 
httplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxhttplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxadampcarr67227
 
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docxodiliagilby
 
Program flowchart
Program flowchartProgram flowchart
Program flowchartSowri Rajan
 

Similar to cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx (20)

4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
 
9.C Programming
9.C Programming9.C Programming
9.C Programming
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020
 
sodapdf-converted into ppt presentation(1).pdf
sodapdf-converted into ppt presentation(1).pdfsodapdf-converted into ppt presentation(1).pdf
sodapdf-converted into ppt presentation(1).pdf
 
C lab manaual
C lab manaualC lab manaual
C lab manaual
 
Write a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfWrite a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdf
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using C
 
Usp
UspUsp
Usp
 
Gps c
Gps cGps c
Gps c
 
#include stdio.h#include stdlib.h#include string.h#inclu.pdf
#include stdio.h#include stdlib.h#include string.h#inclu.pdf#include stdio.h#include stdlib.h#include string.h#inclu.pdf
#include stdio.h#include stdlib.h#include string.h#inclu.pdf
 
Computer Networks Lab File
Computer Networks Lab FileComputer Networks Lab File
Computer Networks Lab File
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
String Manipulation Function and Header File Functions
 
httplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxhttplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docx
 
Unit2 C
Unit2 C Unit2 C
Unit2 C
 
Unit2 C
Unit2 CUnit2 C
Unit2 C
 
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
 
Cquestions
Cquestions Cquestions
Cquestions
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
 

More from gordienaysmythe

CLINICAL SCHOLARSHIPTuberculosis Treatment for Mexican Ame.docx
CLINICAL SCHOLARSHIPTuberculosis Treatment for Mexican Ame.docxCLINICAL SCHOLARSHIPTuberculosis Treatment for Mexican Ame.docx
CLINICAL SCHOLARSHIPTuberculosis Treatment for Mexican Ame.docxgordienaysmythe
 
CLOUD COMPUTINGAssessment item 3 - AWS implementation – 10Ove.docx
CLOUD COMPUTINGAssessment item 3 - AWS implementation – 10Ove.docxCLOUD COMPUTINGAssessment item 3 - AWS implementation – 10Ove.docx
CLOUD COMPUTINGAssessment item 3 - AWS implementation – 10Ove.docxgordienaysmythe
 
Clinical Case Studies8(6) 417 –423© The Author(s) 2009.docx
Clinical Case Studies8(6) 417 –423© The Author(s) 2009.docxClinical Case Studies8(6) 417 –423© The Author(s) 2009.docx
Clinical Case Studies8(6) 417 –423© The Author(s) 2009.docxgordienaysmythe
 
Clinical Case Studies8(5) 383 –402© The Author(s) 2009.docx
Clinical Case Studies8(5) 383 –402© The Author(s) 2009.docxClinical Case Studies8(5) 383 –402© The Author(s) 2009.docx
Clinical Case Studies8(5) 383 –402© The Author(s) 2009.docxgordienaysmythe
 
Climate ChangeWhat every designer should know.This i.docx
Climate ChangeWhat every designer should know.This i.docxClimate ChangeWhat every designer should know.This i.docx
Climate ChangeWhat every designer should know.This i.docxgordienaysmythe
 
CLIENT INTERVIEW SHEETDate ______________.docx
CLIENT INTERVIEW SHEETDate     ______________.docxCLIENT INTERVIEW SHEETDate     ______________.docx
CLIENT INTERVIEW SHEETDate ______________.docxgordienaysmythe
 
Click the link above to submit your assignment.Students, please .docx
Click the link above to submit your assignment.Students, please .docxClick the link above to submit your assignment.Students, please .docx
Click the link above to submit your assignment.Students, please .docxgordienaysmythe
 
click the link and watch the following video death by socialism an.docx
click the link and watch the following video death by socialism an.docxclick the link and watch the following video death by socialism an.docx
click the link and watch the following video death by socialism an.docxgordienaysmythe
 
Click the link above to complete this journal.  The topics of the jo.docx
Click the link above to complete this journal.  The topics of the jo.docxClick the link above to complete this journal.  The topics of the jo.docx
Click the link above to complete this journal.  The topics of the jo.docxgordienaysmythe
 
Classify man from the Domain to the species and discuss each categor.docx
Classify man from the Domain to the species and discuss each categor.docxClassify man from the Domain to the species and discuss each categor.docx
Classify man from the Domain to the species and discuss each categor.docxgordienaysmythe
 
Classroom Discussion is a valuable learning tool in that it.docx
Classroom Discussion is a valuable learning tool in that it.docxClassroom Discussion is a valuable learning tool in that it.docx
Classroom Discussion is a valuable learning tool in that it.docxgordienaysmythe
 
CLASSICSOFWESTERN PHILOSOPHY2CLASSICSO.docx
CLASSICSOFWESTERN PHILOSOPHY2CLASSICSO.docxCLASSICSOFWESTERN PHILOSOPHY2CLASSICSO.docx
CLASSICSOFWESTERN PHILOSOPHY2CLASSICSO.docxgordienaysmythe
 
Classification Alternative Techniques Assignment1) Define a.docx
Classification Alternative Techniques Assignment1) Define a.docxClassification Alternative Techniques Assignment1) Define a.docx
Classification Alternative Techniques Assignment1) Define a.docxgordienaysmythe
 
Classic Combo PlateDirectionsBefore there were all th.docx
Classic Combo PlateDirectionsBefore there were all th.docxClassic Combo PlateDirectionsBefore there were all th.docx
Classic Combo PlateDirectionsBefore there were all th.docxgordienaysmythe
 
Class- As stated on in Chapter 6, Walsh & Sattes (2010) write that” .docx
Class- As stated on in Chapter 6, Walsh & Sattes (2010) write that” .docxClass- As stated on in Chapter 6, Walsh & Sattes (2010) write that” .docx
Class- As stated on in Chapter 6, Walsh & Sattes (2010) write that” .docxgordienaysmythe
 
Classic Gardens and Landscapes counts responses to specialty pro.docx
Classic Gardens and Landscapes counts responses to specialty pro.docxClassic Gardens and Landscapes counts responses to specialty pro.docx
Classic Gardens and Landscapes counts responses to specialty pro.docxgordienaysmythe
 
Class, this is the final forum of the course.  From our readings fro.docx
Class, this is the final forum of the course.  From our readings fro.docxClass, this is the final forum of the course.  From our readings fro.docx
Class, this is the final forum of the course.  From our readings fro.docxgordienaysmythe
 
Class Subjects we went overWEEK 1 April 5thMULTICULTURAL.docx
Class Subjects we went overWEEK 1         April 5thMULTICULTURAL.docxClass Subjects we went overWEEK 1         April 5thMULTICULTURAL.docx
Class Subjects we went overWEEK 1 April 5thMULTICULTURAL.docxgordienaysmythe
 
Class ProfileStudent NameEnglish Language LearnerSocio.docx
Class ProfileStudent NameEnglish Language LearnerSocio.docxClass ProfileStudent NameEnglish Language LearnerSocio.docx
Class ProfileStudent NameEnglish Language LearnerSocio.docxgordienaysmythe
 
Class 2 Why Take CourseShare your professional or personal (.docx
Class 2 Why Take CourseShare your professional or personal (.docxClass 2 Why Take CourseShare your professional or personal (.docx
Class 2 Why Take CourseShare your professional or personal (.docxgordienaysmythe
 

More from gordienaysmythe (20)

CLINICAL SCHOLARSHIPTuberculosis Treatment for Mexican Ame.docx
CLINICAL SCHOLARSHIPTuberculosis Treatment for Mexican Ame.docxCLINICAL SCHOLARSHIPTuberculosis Treatment for Mexican Ame.docx
CLINICAL SCHOLARSHIPTuberculosis Treatment for Mexican Ame.docx
 
CLOUD COMPUTINGAssessment item 3 - AWS implementation – 10Ove.docx
CLOUD COMPUTINGAssessment item 3 - AWS implementation – 10Ove.docxCLOUD COMPUTINGAssessment item 3 - AWS implementation – 10Ove.docx
CLOUD COMPUTINGAssessment item 3 - AWS implementation – 10Ove.docx
 
Clinical Case Studies8(6) 417 –423© The Author(s) 2009.docx
Clinical Case Studies8(6) 417 –423© The Author(s) 2009.docxClinical Case Studies8(6) 417 –423© The Author(s) 2009.docx
Clinical Case Studies8(6) 417 –423© The Author(s) 2009.docx
 
Clinical Case Studies8(5) 383 –402© The Author(s) 2009.docx
Clinical Case Studies8(5) 383 –402© The Author(s) 2009.docxClinical Case Studies8(5) 383 –402© The Author(s) 2009.docx
Clinical Case Studies8(5) 383 –402© The Author(s) 2009.docx
 
Climate ChangeWhat every designer should know.This i.docx
Climate ChangeWhat every designer should know.This i.docxClimate ChangeWhat every designer should know.This i.docx
Climate ChangeWhat every designer should know.This i.docx
 
CLIENT INTERVIEW SHEETDate ______________.docx
CLIENT INTERVIEW SHEETDate     ______________.docxCLIENT INTERVIEW SHEETDate     ______________.docx
CLIENT INTERVIEW SHEETDate ______________.docx
 
Click the link above to submit your assignment.Students, please .docx
Click the link above to submit your assignment.Students, please .docxClick the link above to submit your assignment.Students, please .docx
Click the link above to submit your assignment.Students, please .docx
 
click the link and watch the following video death by socialism an.docx
click the link and watch the following video death by socialism an.docxclick the link and watch the following video death by socialism an.docx
click the link and watch the following video death by socialism an.docx
 
Click the link above to complete this journal.  The topics of the jo.docx
Click the link above to complete this journal.  The topics of the jo.docxClick the link above to complete this journal.  The topics of the jo.docx
Click the link above to complete this journal.  The topics of the jo.docx
 
Classify man from the Domain to the species and discuss each categor.docx
Classify man from the Domain to the species and discuss each categor.docxClassify man from the Domain to the species and discuss each categor.docx
Classify man from the Domain to the species and discuss each categor.docx
 
Classroom Discussion is a valuable learning tool in that it.docx
Classroom Discussion is a valuable learning tool in that it.docxClassroom Discussion is a valuable learning tool in that it.docx
Classroom Discussion is a valuable learning tool in that it.docx
 
CLASSICSOFWESTERN PHILOSOPHY2CLASSICSO.docx
CLASSICSOFWESTERN PHILOSOPHY2CLASSICSO.docxCLASSICSOFWESTERN PHILOSOPHY2CLASSICSO.docx
CLASSICSOFWESTERN PHILOSOPHY2CLASSICSO.docx
 
Classification Alternative Techniques Assignment1) Define a.docx
Classification Alternative Techniques Assignment1) Define a.docxClassification Alternative Techniques Assignment1) Define a.docx
Classification Alternative Techniques Assignment1) Define a.docx
 
Classic Combo PlateDirectionsBefore there were all th.docx
Classic Combo PlateDirectionsBefore there were all th.docxClassic Combo PlateDirectionsBefore there were all th.docx
Classic Combo PlateDirectionsBefore there were all th.docx
 
Class- As stated on in Chapter 6, Walsh & Sattes (2010) write that” .docx
Class- As stated on in Chapter 6, Walsh & Sattes (2010) write that” .docxClass- As stated on in Chapter 6, Walsh & Sattes (2010) write that” .docx
Class- As stated on in Chapter 6, Walsh & Sattes (2010) write that” .docx
 
Classic Gardens and Landscapes counts responses to specialty pro.docx
Classic Gardens and Landscapes counts responses to specialty pro.docxClassic Gardens and Landscapes counts responses to specialty pro.docx
Classic Gardens and Landscapes counts responses to specialty pro.docx
 
Class, this is the final forum of the course.  From our readings fro.docx
Class, this is the final forum of the course.  From our readings fro.docxClass, this is the final forum of the course.  From our readings fro.docx
Class, this is the final forum of the course.  From our readings fro.docx
 
Class Subjects we went overWEEK 1 April 5thMULTICULTURAL.docx
Class Subjects we went overWEEK 1         April 5thMULTICULTURAL.docxClass Subjects we went overWEEK 1         April 5thMULTICULTURAL.docx
Class Subjects we went overWEEK 1 April 5thMULTICULTURAL.docx
 
Class ProfileStudent NameEnglish Language LearnerSocio.docx
Class ProfileStudent NameEnglish Language LearnerSocio.docxClass ProfileStudent NameEnglish Language LearnerSocio.docx
Class ProfileStudent NameEnglish Language LearnerSocio.docx
 
Class 2 Why Take CourseShare your professional or personal (.docx
Class 2 Why Take CourseShare your professional or personal (.docxClass 2 Why Take CourseShare your professional or personal (.docx
Class 2 Why Take CourseShare your professional or personal (.docx
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 

cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx

  • 1. cmdfile.txt sleep 5 ls -latr sleep 3 pwd sleep 1 wc /etc/passwd CommandNode.c #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "CommandNode.h" /** *CommandNode.c *The function bodies for a linked list of commands **/ /** Example of linked list initialization in code:
  • 2. //First command node (head of list) headCommand = (CommandNode*)malloc(sizeof(CommandNode)); CreateCommandNode(headCommand, command, index, NULL); index = 1; ..... //Later command nodes while ((linesize = getline(&line, &len, fp)) >= 0) { ... index++; nextCommand1 = (CommandNode*)malloc(sizeof(CommandNode)); CreateCommandNode(nextCommand1, command, index, NULL); InsertCommandAfter(headCommand, nextCommand1); } **/ //create a new command node. usually nextCmd can be NULL and function InsertCommandAfter can be called to insert after head node. void CreateCommandNode(CommandNode* thisNode, char cmd[20][20], int ind, CommandNode* nextCmd) {
  • 3. //this is useful if you store a string (char *): strcpy(thisNode- >command, cmd); for (int i = 0; i < 20; i++) for (int j = 0; j < 20; j++) thisNode->command[i][j] = cmd[i][j]; thisNode->index = ind; thisNode->nextCommandPtr = nextCmd; return; } //insert node newNode after thisNode void InsertCommandAfter(CommandNode* thisNode, CommandNode* newNode) { CommandNode* tmpNext = NULL; tmpNext = thisNode->nextCommandPtr; thisNode->nextCommandPtr = newNode; newNode->nextCommandPtr = tmpNext; return; }
  • 4. //get next command node in linked list CommandNode* GetNextCommand(CommandNode* thisNode) { return thisNode->nextCommandPtr; } //find a command based on the pid CommandNode* FindCommand(CommandNode* cmd, int pid) { CommandNode* tmpNext = cmd; while (tmpNext != NULL) { if (tmpNext->PID == pid) { return tmpNext; } tmpNext = tmpNext->nextCommandPtr; } return NULL; } CommandNode.h /** *CommandNode.h *The struct for a Command Node and function prototypes for a
  • 5. linked list of commands **/ typedef struct command_struct { char command[20][20]; int index; int PID; int starttime; struct command_struct* nextCommandPtr; } CommandNode; void CreateCommandNode(CommandNode* thisNode, char cmd[20][20], int ind, CommandNode* nextCmd); void InsertCommandAfter(CommandNode* thisNode, CommandNode* newNode); CommandNode* GetNextCommand(CommandNode* thisNode); CommandNode* FindCommand(CommandNode* cmd, int pid);
  • 6. HWdetails&helperFile/HW_details1.jpg HWdetails&helperFile/HW_details1_1.jpg HWdetails&helperFile/read_parse_file.c #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; char newString[20][20]; int i,j,ctr; fp = fopen("commands.txt", "r"); if (fp == NULL) exit(EXIT_FAILURE); while ((read = getline(&line, &len, fp)) != -1) { printf("---------------------------------------n"); printf("nn Split string by space into words :n");
  • 7. printf("Retrieved line of length %zu:n", read); printf("%s", line); for (int i=0; i<20; i++) for (int j=0; j<20; j++) newString[i][j]=0; j=0; ctr=0; for(i=0;i<=(strlen(line));i++) { // if space or NULL found, assign NULL into newString[ctr] if(line[i]==' '||line[i]=='0') { newString[ctr][j]='0'; ctr++; //for next word j=0; //for next word, init index to 0 } else { newString[ctr][j]=line[i]; j++; } } printf("n Strings or words after split by space are :n"); for(i=0;i < ctr;i++) printf(" %sn",newString[i]); } fclose(fp); if (line) free(line);
  • 8. exit(EXIT_SUCCESS); } HWdetails&helperFile/SampleOutput.jpg HWdetails&helperFile/shell1_execvp.c #include "apue.h" #include <sys/wait.h> int main(void) { pid_tpid; int status; char buf[1][5]; char *buf2[6]; buf[0][0] = '.'; buf[0][1] = '.'; buf[0][2] = 0; buf2[0] = "ls"; buf2[1] = "-latr"; buf2[2] = "/etc/passwd"; buf2[3] = (char *)&buf[0][0]; buf2[4] = (char *)0; buf2[5] = (char *)0; if ((pid = fork()) < 0) { err_sys("fork error"); } else if (pid == 0) { /* child */ execvp(buf2[0], buf2); err_ret("couldn't execute: %s", buf2[0]);
  • 9. exit(127); } /* parent */ if ((pid = waitpid(pid, &status, 0)) < 0) err_sys("waitpid error"); printf("DONE "); exit(0); } HWdetails&helperFile/skeleton_solution.c //--------------------------- //fork the commands and record the start times CommandNode *headNode; /** This is the beginning of your linked list of CommandNodes **/ .... CommandNode *tmpNode; tmpNode = headNode; while (tmpNode != NULL) {
  • 10. //save the startime! // tmpNode.starttime = starttime pid = fork(); if (pid < 0) { fprintf(stderr, "error forking"); exit(2); } else if (pid == 0) { /*child */ //See shell1_execvp.c for execvp usage execvp(....tmpNode.command); /*executes the command in the specific node */ } else if (pid > 0) { /* parent goes to the next node */
  • 11. tmpNode.pid = pid; int fdout = open("%d.out", tmpNode.index); int fderr = open("%d.err", tmpNode.index); fprintf(fdout, "Starting command INDEX %d: child PID %d of parent PPID %d.n", tmpNode.index, pid, getpid() ); tmpNode = tmpNode->nextCommandPtr; } } /*end of while loop */
  • 12. //--------------------------- //Final while loop: waits until anything has completed, //this will exit (wait returns -1) //when there is no more child process. Then your parent process exits. while((pid = wait(&status)) >= 0) { if(pid > 0) { //finishtime = get the finish time //search your linked list for the node that corresponds to pid //The function FindNode was provided //node=FindNode(pid) //signal handling int fdout = open("%d.out", node.index); int fderr = open("%d.err", node.index);
  • 13. fprintf(stderr, "Process with PID %d terminated.n", pid); if (WIFEXITED(status)) { fprintf(fderr, "Child %d terminated normally with exit code: %dn", pid, WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { fprintf(fderr, "Child %d terminated abnormally with signal number: %dn", pid, WTERMSIG(status)); } // //to compute the elapsed time you subtract //elapsedtime = finishtime - node.start_time //decide if you will restart //if (elapsedtime > 2) { //record the new starttime // node.starttime = new starttime // pid = fork(); // if (pid < 0) //error
  • 14. // else if (pid == 0) { //child //See shell1_execvp.c for execvp usage // execvp(node.cmd); // } else if (pid > 0) { // node.pid = pid; // } } } time_demo.c /* Program to demonstrate time taken by function fun() */ #include <stdio.h> #include <time.h> // A function that terminates when enter key is pressed void fun() { printf("fun() starts n"); printf("Press enter to stop fun n"); while(1) { if (getchar()) break; } printf("fun() ends n"); }
  • 15. // The main program calls fun() and measures time taken by fun() int main() { // Calculate the time taken by fun() struct timespec start, finish; double elapsed; clock_t t; t = clock(); clock_gettime(CLOCK_MONOTONIC, &start); printf("start %ldn", start.tv_sec); fun(); clock_gettime(CLOCK_MONOTONIC, &finish); printf("finish %ldn", finish.tv_sec); //printf("CLOCKSPERSEC %ldn", CLOCKS_PER_SEC); //double time_taken = ((double)t)*1000.0/CLOCKS_PER_SEC; // in seconds elapsed = (finish.tv_sec - start.tv_sec); //Alternative with more precision: //elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0; printf("fun() took %f seconds to execute n", elapsed); return 0; }