运行 用于备份 Linux 个文件的 C 程序

Running a C program to backup Linux files

正如标题所说,我正在尝试编写一个程序,将文件从源目录(由用户在 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 语句,当 BackupTime 的变量不是从 shell 设置时,它总是有效。设置变量后,程序会在没有任何警告或错误的情况下进行编译,但它绝对不会执行任何操作。我知道 strcmp(backup,time) 部分有效,因为我已经单独打印了它,当它们相同时它 returns 0.

关于如何让它发挥作用有什么想法吗?

上面代码中的问题是您执行了比较但没有在循环中更新 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;
}