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中执行程序的原因。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐