system函数的参数(字符串)是要执行的命令,这个命令可以使用 & 运行后台作业,也可以一次执行多个程序。
示例1:
#include
int
main()
{
int status;
if ( (status = system("ping -c 3")) < 0) {
printf("error occured\n");
}
printf("after???\n");
return 0;
}
运行结果:
PING (180.149.132.47) 56(84) bytes of data.
64 bytes from 180.149.132.47: icmp_seq=1 ttl=48 time=365 ms
64 bytes from 180.149.132.47: icmp_seq=2 ttl=48 time=357 ms
64 bytes from 180.149.132.47: icmp_seq=3 ttl=48 time=372 ms
--- ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2001ms
rtt min/avg/max/mdev = 357.866/365.516/372.928/6.151 ms
after???
示例2:后台作业
#include
int
main()
{
int status;
if ( (status = system("ping -c 3 &")) < 0) {
printf("error occured\n");
}
printf("after???\n");
return 0;
}
运行结果:
after???
PING (180.149.132.47) 56(84) bytes of data.
╭─ ~/Desktop/test
╰─➤ 64 bytes from 180.149.132.47: icmp_seq=1 ttl=48 time=351 ms
64 bytes from 180.149.132.47: icmp_seq=2 ttl=48 time=359 ms
64 bytes from 180.149.132.47: icmp_seq=3 ttl=48 time=347 ms
--- ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 347.331/352.922/359.501/5.040 ms
示例3:一次执行多个命令
#include
int
main()
{
int status;
if ( (status = system("date; ping -c 3")) < 0) {
printf("error occured\n");
}
printf("after???\n");
return 0;
}
运行结果:
Fri Mar 18 22:18:58 CST
PING (123.125.114.144) 56(84) bytes of data.
64 bytes from 123.125.114.144: icmp_seq=1 ttl=48 time=326 ms
64 bytes from 123.125.114.144: icmp_seq=2 ttl=48 time=320 ms
64 bytes from 123.125.114.144: icmp_seq=3 ttl=48 time=325 ms
--- ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 320.754/324.180/326.318/2.534 ms
after???