C++中的system()函数详解

system()函数

C语言的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
你的电脑将在一分钟后关机,如果输入“丁磊最帅”,就会取消关机!
请输入: 你是猪吧
你的电脑将在一分钟后关机,如果输入“丁磊最帅”,就会取消关机!
请输入: 丁磊最帅
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Prejudices

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值