很多时候我们需要在我们所编写的C程序当中,调用一行命令,在命令行运行的命令,比如ifconfig,ls,或者是其他需要的命令如mpirun -machinefile host -np * ./*(MPI并行程序)等等,这就要求我们能够在Linux下调用shell命令。
Linux的C就为我们提供了一个可以调用shell命令的函数,它就是system()。
system函数调用/bin/sh,执行特定的shell命令,阻塞当前的进程直到shell命令执行完毕,才重新回到当前进程。调用它的格式为:
#include <stdlib.h>
int system(const char *command);//command就是我们要执行的各种命令,例如“mpirun -np 2 ./cpi”
执行system实际上是调用了fork函数(产生新进程)、exec函数(在新进程中执行新任务)、waitpid函数(等待新进程结束)。
我们给出一个简单的system函数举例:
#include <stdlib.h>
int main(int argc,char **argv)
{
system("ifconfig");//调用ifconfig
system("mpirun -np 2 ./cpi");//调用mpi并行程序命令
}