简体   繁体   中英

Running a C program to backup Linux files

As the title says, I'm trying to write a program that will backup files from a source directory (set by the user in the shell as an environment variable) to a destination directory (again set by the user in the shell as an environment variable) at a specific backup time (set by the user in the shell as an environment variable - format HH:MM). My code is the following:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>

int main(int argc, char *argv[])
{
  int b=1;
  char backup[100];
  char *source=getenv("BackupSource");
  char *destination=getenv("BackupDestination");
  char *btime=getenv("BackupTime");

  time_t getTime;
  struct tm *actualTime;
  time(&getTime);
  actualTime=localtime(&getTime);
  strftime(backup, 100, "%H:%M", actualTime);

   while(b)
    {
       while(strcmp(backup,btime)!=0)
         {
           sleep(60);
         }
       system("cp -r $BackupSource $BackupDestination");
    }

return 0;
}

My question is the following : when the environment variable for BackupTime is set my inifinte loop doesn't work. I've inserted print statements at every step in the loop and when the variable for BackupTime isn't set from the shell it always works. When the variable is set the program compiles without any warnings or errors but it does absolutely nothing. I know the strcmp(backup,time) part works because I've printed it separately and when they are both the same it returns 0.

Any ideas on how I could make it work?

The problem in the code above is that you perform a comparison but you don't update backup variable value in the loop.

It should look like more:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>

int main(int argc, char *argv[])
{
  int b=1;
  char backup[100];
  char *source=getenv("BackupSource");
  char *destination=getenv("BackupDestination");
  char *btime=getenv("BackupTime");

  time_t getTime;
  struct tm *actualTime;

   while(b)
    {
       //in each loop you get the time so it can be compared with the env variable
       time(&getTime);
       actualTime=localtime(&getTime);
       strftime(backup, 100, "%H:%M", actualTime);

       //no need for a while loop in a while loop
       if(strcmp(backup,btime)==0)
       {
           system("cp -r $BackupSource $BackupDestination");
       }
       sleep(60);
    }

return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM