Question

In: Computer Science

Programming Assignment #2, Processes Write a C program (time_shm.c) that determines the amount of time necessary...

Programming Assignment #2, Processes

  1. Write a C program (time_shm.c) that determines the amount of time necessary to run a command from the command line. This program will be run as

./time <command [args...]>

and will report the amount of elapsed time to run the specified command. This will involve using fork() and execvp() functions, as well as the gettimeofday() function to determine the elapsed time. It will also require the use of two different IPC mechanisms.

The general strategy is to fork a child process that will execute the specified command. However, before the child executes the command, it will record a timestamp of the current time (which we term “starting time”). The parent process will wait for the child process to terminate. Once the child terminates, the parent will record the current timestamp for the ending time. The difference between the starting and ending times represents the elapsed time to execute the command. The example output below reports the amount of time to run the command ls:

./time ls -l

total 156

25616 Feb

4

15:59 a.out

-rwxr-xr-x 1 thomas users

-rw-r--r-- 1 thomas users

252 Feb

4

16:00 output.txt

-rwxr-xr-x 1

thomas users

86024

Feb

2

20:58 project.exe

-rwxr-xr-x 1

thomas users

25616

Feb

2

21:00 time

-rw-r--r-- 1

thomas users

5144

Feb

2

20:58 time.c

Elapsed time: 0.001448 seconds

As the parent and child are separate processes, they will need to arrange how the starting time will be shared between them. You will write one version of this program, representing a method of IPC.

2a) The first version, time_shm.c, will have the child process write the starting time to a region of shared memory before it calls execvp(). After the child process terminates, the parent will read the starting time from shared memory. The region of shared memory should be established before the child process is forked, allowing both the parent and child processes access to the region of shared memory.

You will use the gettimeofday() function to record the current timestamp. This function is passed a pointer to a struct timeval object, which contains two members: tv_sec and tv_usec. These represent the number of elapsed seconds and microseconds since January 1, 1970 (known as the UNIX EPOCH). The following code sample illustrates how this function can be used:

  • Get current time timeval_t startTime; gettimeofday( &startTime, 0 );
  • get the end time

timeval_t end_time;

gettimeofday( &end_time, 0 );

  • calculate elapsed time timeval_t elapsed_time;

timersub( &end_time, startTime, &elapsed_time );

// print elapsed time (microseconds right justified zero filled)

printf( "\nElapsed time: %d.%06d seconds\n", elapsed_time.tv_sec, elapsed_time.tv_usec );

Hint:

  1. For IPC between the child and parent processes, the contents of the shared memory pointer can be assigned the struct timeval representing the starting time. When pipes are used, a pointer to a struct timeval can be written to - and read from - the pipe.
  1. gcc time_shm.c -otime -lrt is an example command to compile and link your program

3.    ./time ls -l | tee time_shm_output.txt is an example command to run your program while collecting your program’s output to a text file and seeing the output on the console.

Solutions

Expert Solution

---------------------------------------------------------------ANSWER-------------------------------------------------------------------------

   #include <fcntl.h>  
   #include <stdio.h>
   #include <unistd.h> 17
   #include <sys/shm.h>
   #include <sys/mman.h>
   #include <sys/time.h>
   #include <sys/wait.h>


#if  
!defined( USING_PIPES )
#define
USING_SHARED_MEMORY // Shared memory will be the default implementation
#define IPC_METHOD "SHARED MEMORY"
#else
   #undef USING_SHARED _MEMORY
#Define IPC_METHOD "Anonymous Pipe"
#endif

int main( int argc, char **argv )
{
if( argc <= 1 )
{
   fprintf( stderr, "usage:   %s [args...]\n", argv[0] );

}
return -1;

typedef struct timeval timeval_t;


#ifdef USING_SHARED_MEMORY
   // Shared memory setup
   // 1) create the shared memory region
   char sharedMemoryName[] = "Command Timer";
   int   sharedMemoryFD   = shm_open( sharedMemoryName, O_CREAT | O_RDWR, 0666 );
   // 2) configure the size of the shared memory region
   ftruncate( sharedMemoryFD, sizeof(timeval_t) );
   // 3) memory map the shared memory region
   timeval_t * sharedMemory = mmap( 0, sizeof(timeval_t), PROT_READ | PROT_WRITE, MAP_SHARED, sharedMemoryFD, 0 );
   #else   // USING_PIPES

//pipe setup
enum {READ_END =0,WRITE _END};
int pipeFD[2];
pipe(pipeFD);
#endif


if( fork() == 0 )
{
   #ifdef USING_SHARED_MEMORY
   // Get and save the current time into shared memory,
   gettimeofday( sharedMemory, 0 );
   #else

close (pipeFD[READ_END]);

timeval_t startTime;
gettimeofday(&startTime,0);
write(pipeFD[write_END],&startTime,sizeof(startTime));
close(pipeFD[WRITE_END]);
#endif


   execvp( argv[1], argv + 1 );
   else // parent process
   wait( 0 ); 129
   // get the end time
   timeval_t end_time;
   gettimeofday( &end_time, 0 );
   // get the start time
   timeval_t   startTime;
#ifdef USING_SHARED_MEMORY
startTime = *sharedMemory;
   // The child placed the start time in shared memory
shm_unlink(sharedMemoryName);
#else   // USING_PIPES
close(pipeFD[WRITE_END]);
read (pipeFD[READ_END], &startTime,sizeof(startTime));
close(pipeFD[READ_END]);
#endif
// calculate elapsed time
   timeval_t elapsed_time;
   timersub( &end_time, &startTime, &elapsed_time );

   // print microseconds right justified zero filled
   printf( "\nElapsed time: %d.%06d seconds\n", elapsed_time.tv_sec, elapsed_time.tv_usec );
   printf( "IPC Method: %s\nCommand: ", IPC_METHOD);
   char ** arg = argv + 1;
   while( *arg ) printf("%s ", *arg++);
   printf("\n");
}
   return 0;
}

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

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


Related Solutions

C PROGRAMMING – Steganography In this assignment, you will write an C program that includes processing...
C PROGRAMMING – Steganography In this assignment, you will write an C program that includes processing input, using control structures, and bitwise operations. The input for your program will be a text file containing a large amount of English. Your program must extract the “secret message” from the input file. The message is hidden inside the file using the following scheme. The message is hidden in binary notation, as a sequence of 0’s and 1’s. Each block of 8-bits is...
Programming Assignment 1 Performance Assessment Objective: To write a C program (not C++) that calculates the...
Programming Assignment 1 Performance Assessment Objective: To write a C program (not C++) that calculates the average CPI, total processing time (T), and MIPS of a sequence of instructions, given the number of instruction classes, the CPI and total count of each instruction type, and the clock rate (frequency) of the machine. The following is what the program would look like if it were run interactively. Your program will read values without using prompts. Inputs: • Clock rate of machine...
Programming Language: C++ Overview For this assignment, write a program that will simulate a single game...
Programming Language: C++ Overview For this assignment, write a program that will simulate a single game of Craps. Craps is a game of chance where a player (the shooter) will roll 2 six-sided dice. The sum of the dice will determine whether the player (and anyone that has placed a bet) wins immediately, loses immediately, or if the game continues. If the sum of the first roll of the dice is equal to 7 or 11, the player wins immediately....
6- Write a C++ program that determines the amount of memory used by char, short int,...
6- Write a C++ program that determines the amount of memory used by char, short int, unsigned short int, float, and double types and display the information on the screen. You program should also display the typical range for each data type.
Programming assignment 4 : C++ Write a program to do the following: 1.Define a structure to...
Programming assignment 4 : C++ Write a program to do the following: 1.Define a structure to store a date, which includes day(int), month(int), and year(int). 2.Define a structure to store an address, which includes address(house number and street)(string), city(string), state(string), zip code (string). 3.Define a class to store the following information about a student. It should include private member variables: name(string), ID (int), date of birth (the first structure), address (the second structure), total credit earned (int), and GPA (double)....
Python programming c++ Write a program that computes the amount of money the cheerleaders raised during...
Python programming c++ Write a program that computes the amount of money the cheerleaders raised during their candy bar fundraiser using the following data: 12 bars per case. The candy was sold for $1.00 per bar. Each case cost $8.00. They are required to give the student government association 10% of their earnings. The program should ask the user how many bars were sold. The program should calculate and display the SGA proceed's, the Cheer team's proceeds, and the appropriate...
Programming II: C++ - Programming Assignment Vector Overloads Overview In this assignment, the student will write...
Programming II: C++ - Programming Assignment Vector Overloads Overview In this assignment, the student will write a C++ program that overloads the arithmetic operators for a pre-defined Vector object. When completing this assignment, the student should demonstrate mastery of the following concepts: · Object-oriented Paradigm · Operator Overloading - Internal · Operator Overloading - External · Mathematical Modeling Assignment In this assignment, the student will implement the overloaded operators on a pre-defined object that represents a Vector. Use the following...
This C++ assignment asks to write a function that determines if a C-string begins with a...
This C++ assignment asks to write a function that determines if a C-string begins with a specified prefix. It should have the following signature: bool starts(char *str, char *prefix) It should return true if str begins with prefix, false if not. It should return false if prefix is longer than str. See the table below for some examples of what your function should return for various cases: str prefix returns airplanes air true airplanes abc false airplanes plane false airplanes...
2. Write a program C++ that asks the user for a number (not necessary to force...
2. Write a program C++ that asks the user for a number (not necessary to force any particular requirements). Write a function with the following signature: double square(double x) that returns the square of the user's number (x * x). 3. Write a C++ program that asks the user for an integer. Write a function that returns 1 of the number is even, and 0 if the number is odd. Use this function signature: int isEven(int x). 4. Write a...
using C program Assignment Write a computer program that converts a time provided in hours, minutes,...
using C program Assignment Write a computer program that converts a time provided in hours, minutes, and seconds to seconds Functional requirements Input MUST be specified in hours, minutes, and seconds MUST produce the same output as listed below in the sample run MUST correctly compute times Nonfunctional requirements MUST adhere to program template include below MUST compile without warnings and errors MUST follow the code template provided in this assignment MUST NOT change " int main() " function MUST...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT