Search code examples
clinuxoperating-systemcommand

Determine elapsed time


I am writing a C program that measures the amount of time necessary to run a command from the command line. The strategy is that fork a child process to execute the command and record a timestamp for starting time. The parent process will wait for the child process terminates and record the ending time. The elapsed time is the difference between ending time and starting time. Parent and child communicate through shared memory. However, I found that parent process does not receive starting time of child process. Is my shared memory wrong?

The code is below.

#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>

#define BUFFER_SIZE 10

typedef struct {
    time_t sec;
    suseconds_t msec;
} item;

item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;

int main()
{
pid_t pid;
    char *ls;
    scanf("%s", ls);

    /* fork a child process */
    pid = fork();

    if (pid == 0) { /* child process */
        struct timeval current;
        gettimeofday(&current, NULL);
        
        item starting_time;
        starting_time.sec = current.tv_sec;
        starting_time.msec = current.tv_usec;
        
        buffer[in] = starting_time;
        execlp(ls, "ls", NULL);
    }
    else { /* parent process */
        wait(NULL);
        
        item starting_time;
        starting_time = buffer[out];
        
        struct timeval current;
        gettimeofday(&current, NULL);
        
        long seconds = current.tv_sec - starting_time.sec;
        printf("The elapsed time is: %ld", seconds);
        
    }
}

Another thing is that I don't know how to run a command beside executing C program in terminal like below

./time ls
time.c
time

Elapsed time: 0.25422

Solution

  • item buffer[BUFFER_SIZE];
    ...
    pid = fork();
    

    That's not shared memory. Fork will create new process with a copy of everything, the copied buffer is independent of the old one, changes do not propagate.

    Have some random intro about shared memory I found: https://www.tutorialspoint.com/inter_process_communication/inter_process_communication_shared_memory.htm

    or including fork: https://www.geeksforgeeks.org/fork-memory-shared-bw-processes-created-using/

    Fortunately you don't really need shared memory for this, just measure the starting time before calling fork.

    struct timeval starting_time;
    gettimeofday(&starting_time, NULL);
    pid = fork();
     
    if (pid == 0) { /* child process */
        execlp(ls, "ls", NULL);
    }
    else { /* parent process */
        wait(NULL);
                
        struct timeval current;
        gettimeofday(&current, NULL);
        
        long seconds = current.tv_sec - starting_time.sec;
        printf("The elapsed time is: %ld", seconds);
        
    }