I have a program, where part of it is supposed to show the uptime every 5 seconds but right now it's just showing it one time than telling the program to exit. Why is this child process only going one time and than going to the parent for program exit?
My code is this:
#include "time.h"
void showClock(){
time_t timeNow;
struct tm *locTime;
while(Timer>0){
timeNow=time(NULL);
locTime=localtime(&timeNow);
cout<<"Time is "<<locTime->tm_hour<<":"<<locTime->tm_min<<":"<<locTime->tm_sec<<"\n";
Timer--;
sleep(1);
}
exit(0);
}
void showUpTime(){
char buffer[30] = "/usr/bin/uptime";
char* const args[] = {buffer, (char*) 0};
while(Timer>0){
cout<<"Uptime :"<<execv(buffer, args)<<"\n";
Timer-=5;
sleep(5);
}
exit(0);
}
void countDown(){
int min;int sec;
while(Timer>0){
min=Timer/60;
sec=Timer%60;
cout<<"Timer "<<min<<":"<<sec<<"\n";
Timer--;
sleep(1);
}
exit(0);
}
int main(int argc,char *argv[]){
if(argc<2)
Timer=10;
else
Timer=atoi(argv[1]);
pid_t pid;
int N=3,i;
int status;
if(!fork())showClock();
if(!fork())showUpTime();
if(!fork())countDown();
wait(&status);//parent waits;
cout<<"Program Exits Now\n";
return 0;
}
The problem is in the showUpTime() function. In that function, execv(...) is called to execute uptime. When execv(...) is executed, the current process continues by loading the uptime executable over the previously running program, and exits after uptime program finishes its execution. As wait(&status) waits for any child process to exit, you observed that the main process exited, and the two other child processes were still executing.
The following is the modified code for showUpTime().It should fix the problem:
void showUpTime(){
char buffer[30] = "/usr/bin/uptime";
char* const args[] = {buffer, (char*) 0};
while(Timer>0){
pid_t pid = fork();
if (pid == 0)
cout<<"Uptime :"<< execv(buffer, args)<<"\n";
Timer-=5;
sleep(5);
}
exit(0);
}