调用命令行的函数

溪西创客小屋

C语言有一个system函数(在<stdlib.h>头中,C++则为<cstdlib>头),可以用来调用终端命令。原型如下:

int system(const char *cmdline /* 命令字符串 */
);

例如,Linux系统中,调用system("ls -la");将输出当前目录下的所有文件详细信息。

Windows系统的“终端”(命令提示符)和Linux中的终端不一样,Windows系统中要实现同样功能,需要调用system("dir /a");

以下转自:http://baike.baidu.com/subview/627587/14965930.htm

system

(函数)

编辑

Windows函数编辑

windows操作系统下system () 函数详解(主要是在C语言中的应用) 函数名: system
功 能: 发出一个DOS命令
用 法: int system(char *command);
system函数需加头文件<stdlib.h>后方可调用
程序例:
1
2
3
4
5
6
7
8
#include <stdlib.h>
#include <stdio.h>
int  main( void )
{
printf ( "About to spawn and run a DOS command\n" );
system ( "dir" );
return  0;
}
又如:system("pause")可以实现冻结屏幕,便于观察程序的执行结果;system("CLS")可以实现清屏操作。而调用color函数可以改变控制台的前景色和背景,具体参数在下面说明。
例如,用 system("color 0A"); 其中color后面的0是背景色代号,A是前景色代号。各颜色代码如下:
0=黑色 1=蓝色 2=绿色 3=湖蓝色 4=红色 5=紫色 6=黄色 7=白色 8=灰色 9=淡蓝色 A=淡绿色 B=淡浅绿色 C=淡红色 D=淡紫色 E=淡黄色 F=亮白色
(注意: Microsoft Visual C++6.0 支持system)
举例
看了下面实例,相信你会对学到更多system在C程序设计中的应用。
例一:
C语言调用DOS命令实现 定时关机
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int  print()
{
printf ( " ╪╪╪╪╪╪╧╧╧╧╧╧╧╧╪╪╪╪╪╪\n" );
printf ( "╔═══╧╧C语言关机程序 ╧╧═══╗\n" );
printf ( "║※1.实现10分钟内的定时关闭计算机 ║\n" );
printf ( "║※2.立即关闭计算机  ║\n" );
printf ( "║※3.注销计算机  ║\n" );
printf ( "║※0.退出系统  ║\n" );
printf ( "╚═══════════════════╝\n" );
return  0;
}
void  main()
{
system ( "title C语言关机程序" ); //设置cmd窗口标题
system ( "mode con cols=48 lines=25" ); //窗口宽度高度
system ( "color 0B" );
system ( "date /T" );
system ( "TIME /T" );
char  cmd[20]= "shutdown -s -t " ;
char  t[5]= "0" ;
print();
int  c;
scanf ( "%d" ,&c);
getchar ();
switch (c)
{
case  1: printf ( "您想在多少秒后自动关闭计算机?(0~600)\n" ); scanf ( "%s" ,t);
system ( strcat (cmd,t)); break ;
case  2: system ( "shutdown -p" ); break ;
case  3: system ( "shutdown -l" ); break ;
case  0: break ;
default : printf ( "Error!\n" );
}
system ( "pause" );
exit (0);
}
例二:
用C语言删除文件,例如文件的位置是d:\123.txt
用system()函数执行windows命令。
1
2
3
4
5
6
7
#include <stdlib.h>
#include <stdio.h>
int  main( void )
{
system ( "del d:\\123.txt" );
return  0;
}

Linux/Unix函数编辑

函数详解
(执行shell 命令)
相关函数
表头文件
#include< stdlib.h>
定义函数
int system(const char * string);
函数说明
system()会调用 fork()产生子进程,由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命令执行完后随即返回原调用的进程。在调用system()期间SIGCHLD 信号会被暂时搁置,SIGINT和SIGQUIT 信号则会被忽略。
返回值
如果fork()失败 返回-1:出现错误
如果exec()失败,表示不能执行Shell,返回值相当于Shell执行了 exit(127)
如果执行成功则返回子Shell的终止状态
如果system()在调用/bin/sh时失败则返回127,其他失败原因返回-1。若参数string为空指针(NULL),仅当命令处理程序可用时,返回非零值,可以通过这一特征判断在一个给定的操作系统上是否支持system函数(当system函数返回值为0时,表明system函数无效,在UNIX系统中,system函数总是可用的);。如果system()调用成功则最后会返回执行shell命令后的返回值,但是此返回值也有可能为 system()调用/bin/sh失败所返回的127,因此最好能再检查errno 来确认执行成功。
附加说明
在编写具有SUID/SGID权限的程序时请勿使用system(),system()会继承环境变量,通过环境变量可能会造成系统安全的问题。
范例
1
2
3
4
5
#include<stdlib.h>
main()
{
system (“ls -al /etc/passwd /etc/shadow”);
}
执行结果:
-rw-r--r-- 1 root root 705 Sep 3 13 :52 /etc/passwd
-r--------- 1 root root 572 Sep 2 15 :34 /etc/shado
例2:
1
2
3
char  tmp[];
sprintf (tmp, "/bin/mount -t vfat %s /mnt/usb" ,dev);
system (tmp);
其中dev是/dev/sda1.
与exec的区别
1、system()和 exec()都可以执行进程外的命令,system是在原进程上开辟了一个新的进程,但是exec是用新进程(命令)覆盖了原有的进程
2、system()和exec()都有能产生返回值,system的返回值并不影响原有进程,但是exec的返回值影响了原进程
以下转自: http://baike.baidu.com/view/2445803.htm

头文件

编辑

1
#include <stdio.h>

函数定义编辑

1
2
FILE  * popen (  const  char  * command ,  const  char  * type );
int  pclose (  FILE  * stream );

函数说明编辑

popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以 运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样。
type 参数只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 "r" 则文件指针连接到 command 的标准输出;如果 type 是 "w" 则文件指针连接到 command 的标准输入。
command 参数是一个指向以 NULL 结束的 shell 命令字符串的 指针。这行命令将被传到 bin/sh 并使用-c 标志,shell 将执行这个命令。
popen 的返回值是个标准 I/O 流,必须由  pclose 来终止。前面提到这个流是单向的。所以向这个流写内容相当于写入该命令的标准输入;命令的标准输出和调用  popen 的进程相同。与之相反的,从流中读数据相当于读取命令的标准输出;命令的标准输入和调用  popen 的进程相同。

返回值编辑

如果调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL,否则返回标准 I/O 流。

返回错误编辑

popen 没有为 内存分配失败设置 errno 值。
如果调用 fork() 或 pipe() 时出现错误,errno 被设为相应的错误类型。
如果 type 参数不合法,errno将返回EINVAL。

使用举例编辑

1
2
3
4
5
6
7
8
9
10
11
if ((fp=popen( "/usr/bin/uptime" , "r" ))==NULL)
{
     sprintf (buf, "error:%s\n" , strerror ( errno ));
     .... //异常处理
}
else
{
     ....
}
     pclose(fp);
}

真实示例编辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#define _LINE_LENGTH 300
int  get_path_total( const  char  *path,  long  long * total) {
     int  err=-1;
     FILE  *file;
     char  line[_LINE_LENGTH];
     char  *p;
     char  tmp[100];
     char  *token;
     sprintf (tmp,  "df %s" , path);
     file = popen(tmp,  "r" );
     if  (file != NULL) {
         if  ( fgets (line, _LINE_LENGTH, file) != NULL) {
             if  ( fgets (line, _LINE_LENGTH, file) != NULL) {
                 token =  strtok (line,  " " );
                 if  (token != NULL) {
                 // printf("token=%s\n", token);
             }
             token =  strtok (NULL,  " " );
             if  (token != NULL) {
             // printf("token=%s\n", token);
             *total=atoll(token)/1024; //k/1024
             err=0;
             }
         }
     }
     pclose(file);
     }
return  err;
}

    使用C++时,有些时候我们可以通过管道的方法来获取所执行的命令所输出的内容。具体做法如下:
    首先你需要确定你所执行的命令所输出的内容的格式(不同的操作系统相同的命令所输出来的内容格式可能会不一致)。我们来举例说明:我想获取/var目录当前所暂用的存储空间,以KB为单位输出:

    [root@localhost /]# du -sk /var
    13532132 var
    [root@localhost /]# du -sk /var | awk -F ' ' '{print $1}'
    13532132
    从上面输出可以知道/var目录当前暂用了13532132KB,那么我们如何将改值使用到我们的程序中呢?为了简单起见我实现了如下函数:

[cpp]  view plain copy
  1. int64_t CalculateDirUsedCapacity (const std::string& directoryName)  
  2. {  
  3.     FILE *fstream = NULL;  
  4.     char buff[32];  
  5.     memset (buff ,'\0'sizeof(buff));  
  6.   
  7.     std::string cmd = "du -sk " + directoryName;  
  8.     cmd += "| awk -F ' ' '{print $1}'";  
  9.   
  10.     // 通过管道来回去系统命令返回的值  
  11.     if(NULL == (fstream = popen (cmd.c_str (), "r"))) {  
  12.         return 0;  
  13.     }  
  14.   
  15.     if(NULL == fgets (buff, sizeof(buff), fstream))     
  16.     {      
  17.         pclose(fstream);    
  18.         return 0;  
  19.     }  
  20.   
  21.     std::strstream ss;  
  22.     ss << buff;  
  23.     int64_t usedCapacity = 0;  
  24.     ss >> usedCapacity;  
  25.     pclose(fstream);  // close pipe  
  26.   
  27.     return usedCapacity;  
  28. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python可以使用内置的subprocess模块来调用命令行。使用subprocess模块,可以在Python程序中执行命令行命令,并获得输出结果。 下面是一个使用subprocess模块执行命令行的示例: ```python import subprocess # 执行ls命令,并将输出结果保存到output变量中 output = subprocess.check_output(["ls", "-l"]) # 将输出结果转换成字符串,并打印出来 print(output.decode("utf-8")) ``` 在这个示例中,`subprocess.check_output()`方法接受一个包含命令行命令及其参数的列表作为参数,并返回命令的输出结果。该示例中执行的命令是`ls -l`,它会列出当前目录下的所有文件和文件夹,并将结果保存在output变量中。`output.decode("utf-8")`将输出结果转换成字符串,并打印出来。 ### 回答2: Python可以通过调用命令行实现与操作系统交互和执行命令。 在Python中,可以使用内置的`os`模块来调用命令行。`os`模块提供了许多函数来执行与操作系统相关的操作,包括调用命令行。 以下是使用Python调用命令行的简单示例: ```python import os # 调用命令行执行一个简单的命令 os.system("dir") # 在Windows上列出当前目录的内容 os.system("ls") # 在Linux或Mac上列出当前目录的内容 # 调用命令行执行带参数的命令 os.system("python myscript.py arg1 arg2") # 执行名为"myscript.py"的Python脚本,并传递两个参数 # 使用subprocess模块更强大的调用命令行 import subprocess # 执行命令并获取输出 output = subprocess.check_output("echo Hello, World!", shell=True) print(output) # 使用管道连接多个命令 p1 = subprocess.Popen("echo Hello", shell=True, stdout=subprocess.PIPE) p2 = subprocess.Popen("wc -c", shell=True, stdin=p1.stdout, stdout=subprocess.PIPE) output = p2.communicate()[0] print(output) ``` 需要注意的是,使用`os.system`执行命令时,命令是在新的命令行窗口中执行的。如果要获取命令执行的结果,可以使用`subprocess`模块提供的函数,如`subprocess.check_output`。 此外,还有其他的第三方库,如`sh`、`pexpect`等,可以在Python中更方便地调用命令行。这些库提供了更多的功能和选项,可以满足更复杂的需求。 ### 回答3: Python调用命令行是通过subprocess模块实现的。 subprocess模块允许Python脚本在运行时创建并控制新的进程,包括调用命令行程序。你可以使用subprocess模块执行命令行命令,并获取其输出或错误信息。 要调用命令行,需要使用subprocess模块的Popen函数。你可以将命令行命令作为参数传递给Popen函数,并通过设置参数来控制进程的行为和输出。 通过subprocess模块,你可以执行各种命令行操作,如运行外部程序、执行Shell脚本、执行系统命令等。 以下是一个简单的例子,演示如何使用subprocess模块调用命令行: ```python import subprocess # 执行命令行命令并获取输出 result = subprocess.run(['ls', '-l'], capture_output=True, text=True) print(result.stdout) # 执行命令行命令并获取返回值 result = subprocess.run(['git', 'commit', '-m', 'Initial commit']) print(result.returncode) ``` 在这个例子中,我们使用subprocess的run函数来执行两个不同的命令行命令。第一个命令是'ls -l',它会列出当前目录下的文件和文件夹的详细信息。我们使用capture_output参数来捕获命令的输出,并使用text参数将输出转换为字符串。第二个命令是'git commit -m "Initial commit"',它会提交一个Git版本控制的新提交。 这只是subprocess模块的一小部分功能,它还有很多其他的用法和选项,可以根据具体需求进行调整。使用subprocess模块,Python可以方便地调用命令行,并与命令行程序进行交互。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值