system函数
该函数是标准库中的函数,头文件为#include <stdlib>
,本质上是shell中执行命令/程序。
我们编写代码如下:
#include <iostream>
#include <unistd.h>
using namespace std;
int main(){
cout << getpid() << ":" << getppid() << endl;
system("./loop");
cout << getpid() << ":" << getppid() << endl;
}
其中的loop是g++ loop.cpp -o loop
生成的可执行文件,具体代码如下:
#include <iostream>
#include <unistd.h>
using namespace std;
int main(){
for(int i=0; i<5; ++i){
cout << getpid() << ":" << getppid() << endl;
}
}
执行结果如下:
我们发现当前进程ID为15216,该进程的父进程为3028。该进程执行system
函数,首先会创建一个shell进程,该进程ID为15216,在这个shell里将会执行可执行文件loop
,创建新进程,该进程ID为15217。这也是我们说system
函数本质上是在shell中执行程序的原因。