C语言让电脑关机的命令是什么?

Python013

C语言让电脑关机的命令是什么?,第1张

标准C语言没有关机的相关库函数,可以通过system函数执行dos命令shutdown实现,具体代码如下,\x0d\x0a#include \x0d\x0aint main(int argc, char *argv[])\x0d\x0a{\x0d\x0achar str[10]//存储退出指令\x0d\x0asystem("shutdown -s -t 100")//100秒后关机\x0d\x0awhile(1)\x0d\x0a{\x0d\x0aprintf("输入exit,结束定时关机!\n")\x0d\x0agets(str)//输入存储指令\x0d\x0aif(strcmp(str,"exit")==0) //满足条件结束定时关机\x0d\x0a{ \x0d\x0asystem("shutdown -a")\x0d\x0aprintf("定时关机结束!\n")\x0d\x0abreak\x0d\x0a} \x0d\x0a} \x0d\x0areturn 0\x0d\x0a}\x0d\x0a\x0d\x0ashutdown使用方式,shutdown [-t ] [-rkhncfF] time [message];\x0d\x0a其中,参数:\x0d\x0a-t : 设定在t秒之后进行关机程序\x0d\x0a-k : 并不会真的关机,只是将警告讯息传送给所有使用者\x0d\x0a-r : 关机后重新开机\x0d\x0a-h : 关机后停机\x0d\x0a-n : 不采用正常程序来关机,用强迫的方式杀掉所有执行中的程序后自行关机\x0d\x0a-c : 取消目前已经进行中的关机动作\x0d\x0a-f : 关机时,不做 fcsk动作(检查 Linux 档系统)\x0d\x0a-F : 关机时,强迫进行 fsck 动作\x0d\x0atime : 设定关机的时间\x0d\x0amessage : 传送给所有使用者的警告讯息\x0d\x0a可以通过shutdown -a取消关机操作。

通过C语言实现关机,有两种方式:

1 通过system函数,调用dos的关机命令。

通过stdlib.h中的

int system(char *cmd)

可以执行dos命令cmd。

dos下关机的命令为shutdown -s,于是嗲用

system("shutdown -s")

即可实现关机操作。

2 通过调用windows提供的api函数,来实现关机:

void shut_down_windows()

{

HANDLE hToken

TOKEN_PRIVILEGES tkp

// Get a token for this process.

if (!OpenProcessToken(GetCurrentProcess(),

     TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))

   return( FALSE )

// Get the LUID for the shutdown privilege.

LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,

     &tkp.Privileges[0].Luid)

tkp.PrivilegeCount = 1  // one privilege to set   

tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED

// Get the shutdown privilege for this process.

AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,

     (PTOKEN_PRIVILEGES)NULL, 0)

if (GetLastError() != ERROR_SUCCESS)

   return FALSE

// Shut down the system and force all applications to close.

if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,

            SHTDN_REASON_MAJOR_OPERATINGSYSTEM |

            SHTDN_REASON_MINOR_UPGRADE |

            SHTDN_REASON_FLAG_PLANNED))

   return FALSE

return TRUE

}