new user so I'm sorry if this explanation isn't clear enough...I am having trouble creating timespec variables to be modified/used between multiple source files. My program is meant to determine the time it takes to execute another program from within my initial program and therefore I'll need to clock the time in two source files and store it to be used later to determine the difference in time. I have been scouring the internet and tried different things but it always seems like my source files create different instances of the variables
Here's what my code basically looks like:
Header file:
//shared.h
#ifndef shared_h
#define shared_h
#include<time.h>
extern struct timespec callTime, startTime;
#endif
Source File1:
//shared.c
#include "shared.h"
struct timespec startTime = {0}, callTime = {0};
Source File2:
//app.c
#include "shared.h"
#include <time.h>
void main(){
clock_gettime(CLOCK_MONOTONIC, &startTime);
}//end of main
Source File:
//timer.c
#include "shared.h"
#include <time.h>
void main(){
pid_t pid = fork();
clock_gettime(CLOCK MONOTONIC, &callTime);
if(pid == 0){
execvp("./app", NULL);
return 0;
}//end of if
printf("Call: %ld & Start: %ld\n", callTime.tv_sec, startTime.tv_sec);
return 0;
}//end of main
I will get something like...
Call: 14928304940 & Start: 0
Hopefully this code gets the point across of what I'm trying to do. When it forks and executes the other program, the value for startTime will change but won't hold so that when I call it later in the Parent process. The value will just be it's initial value instead of the clocked time. it seems Any thoughts on the matter would be greatly appreciate!
Added Note: I do link shared.c with timer.c and app.c seperately and then run timer.c
gcc shared.h
gcc -c shared.c
gcc -c app.c
gcc -c timer.c
gcc -o app app.o shared.o
gcc timer.o shared.o
./a.out
I think your problem here is a misunderstanding of what fork
does. It gives the child process a copy of the parent processes memory. Not the same memory.... well actually on sane architectures it IS the same memory w/o copy-on-write semantics, but don't worry about that for now.
Your child process (assuming app.c
compiles to app
here) will modify its own copy of startTime then exit w/o modifying the parent processes startTime variable.
If you want to have the child process communicate something back to the parent, you need to use some form of interprocess communication.