linux系统编程:系统函数system

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值