system()函数
#include <stdlib>
/* Execute the given line as a shell command.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int system (const char *__command) __wur;
system()
函数执行dos(windows系统) 或 shell(Linux/Unix系统) 命令,参数字符串command为命令名(windows系统下参数字符串不区分大小写)
- 在windows系统中,system函数直接在控制台调用一个command命令
- 在Linux/Unix系统中,system函数会调用fork函数产生子进程,由子进程来执行command命令,命令执行完后随即返回原调用的进程
示例:
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main(void)
{
string input;
system("shutdown -t 60");
//这是Windows系统下的一个关机命令
while (true)
{
cout << "你的电脑将在一分钟后关机,如果输入“丁磊最帅”,就会取消关机!\n请输入: ";
cin >> input;
if (input.compare("丁磊最帅") == 0)
{
system("shutdown -c"); //取消关机命令
break;
}
}
return 0;
}
打印输出:
prejudice@prejudice-VirtualBox:~/Cplus_learning/bin$ ./system
Shutdown scheduled for Wed 2022-06-15 21:58:21 CST, use 'shutdown -c' to cancel.
你的电脑将在一分钟后关机,如果输入“丁磊最帅”,就会取消关机!
请输入: hhhh
你的电脑将在一分钟后关机,如果输入“丁磊最帅”,就会取消关机!
请输入: 你是猪吧
你的电脑将在一分钟后关机,如果输入“丁磊最帅”,就会取消关机!
请输入: 丁磊最帅