断网,启用网络,关机的实现。

windows 下实现 shutdown_two.c 此为第三版

    //	我需要一个断开网络,启用网络,定时发送邮件后关机的功能,其中定时发送邮件功能是邮件客户端完成;原来的工具是用bat实现的,后来给BAT内容放到C中,延时部分用的还是 choice ,因此需要手工输入延时时间。
    //	后来想做个自动计算时间的方法,后来发现sleep用这个功能,遂写了这个功能。说个小插曲,这是第三版,第一版是bat文件,第二版是shutdown.c文件,它生成shutdown.exe文件,注意这个文件名,因为第二版是需要输入当前时间和定时启用网络时间的差值来决定延时多久;
//      这版shutdown_two.c生成的文件shutdown_two.exe和shutdown.exe在同一目录下,执行的时候到shutdown命令时,会先在当前目录下先寻找有无shutdown命令并调用,所以每次执行shutdown_two.exe时都会在关机时提示Please input the hour:,所以一直无法关机。

#include <stdio.h>
#include <string.h> 
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
     int hour, sec;
     int n, m;
     time_t a;
     time(&a);       // a值为时间戳
     printf("a:%lld
", a);
     printf("the time is %s", ctime(&a));   // 细分时间格式

      struct tm t;          // 定义成员 t
      time_t bell;          // 时间类型
//      char str[80];         
      t.tm_sec=0;
      t.tm_min=0;
      t.tm_hour=10;
      t.tm_mday=info->tm_mday;  //通过info->tm_mday获得月中某天,info为已获得的系统时间。
      t.tm_mon=info->tm_mon;    //通过info->tm_mon获得月份
      t.tm_year=info->tm_year;  // 通过info->tm_year获得年份

      bell = mktime(&t);
      printf("the bell time is %lld
", bell);
      hour = ((long int)difftime(bell,a)) / 3600;
      sec = ((long int)difftime(bell,a)) % 3600;
      printf("The sleep time %d hour, %d sec
", hour, sec);

      printf("chazhi is %ld
",(long int)difftime(bell,a));

      system("netsh interface set interface name="WIFI" admin=disabled");
      for (n = 0; n < (long int)difftime(bell,a) ; ++n)
      {
            sleep(1);
      }

      system("netsh interface set interface name="WIFI" admin=enabled");


      for (m = 0; m < (long int)difftime(bell,a) ; ++m)
      {
            sleep(1);
      }
      system("shutdown -f -s -t 0");    // 文件名起的不要和你调用的系统命令重名
                                        // 程序会先在本目录下找是否有同名的exe文件
                                        // 有就会调用,这样就无法执行系统命令

    return 0;
}


下面是第二版

#  第二版
#include <stdio.h>
#include <stdlib.h>
int main(void)
{

    int min, hour, n;
    printf("Please input the hour: ");
    scanf("%d", &hour);
    printf("Please input the minute: ");
    scanf("%d", &min);


    system("netsh interface set interface name="WIFI" admin=disabled");
    for (n = 0; n < hour; ++n)
        system("choice /c k /n /t 3600 /d k 1>nul");
    
    char string[100];
    min *= 60;
    sprintf(string, "choice /c k /n /t %d  /d k 1>nul", min);
    system(string);


    system("netsh interface set interface name="WIFI" admin=enabled");

    system("choice /c k /n /t 600 /d k 1>nul");
    system("shutdown -f -s -t 20");


    return 0;
}
原文地址:https://www.cnblogs.com/EisNULL/p/10838496.html