运行C程序备份Linux文件

问题描述 投票:0回答:1

正如标题所说,我正在尝试编写一个程序,它将文件从源目录(由shell中的用户设置为环境变量)备份到目标目录(再次由shell中的用户设置为环境变量)在特定的备份时间(由shell中的用户设置为环境变量 - 格式HH:MM)。我的代码如下:

#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;
}

我的问题如下:当设置BackupTime的环境变量时,我的inifinte循环不起作用。我已经在循环的每一步插入了print语句,并且当没有从shell设置BackupTime的变量时它始终有效。当设置变量时,程序编译时没有任何警告或错误,但它绝对没有。我知道strcmp(备份,时间)部分有效,因为我已经单独打印它们,当它们都是相同的时候它会返回0。

关于如何使其发挥作用的任何想法?

c linux shell backup
1个回答
1
投票

上面代码中的问题是您执行比较但不更新循环中的backup变量值。

它看起来应该更像:

#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.