C++使用system创建进程

一 点睛

system的原型如下, 其作用是运行以字符串参数的形式传递给它的命令并等待该命令的完成。其作用等价于在shell中执行命令sh -c string。

#include <stdlib.h>
int system(const char *string);

二 代码

#include <stdlib.h>
#include <stdio.h>

int main()
{
    printf("running cat with system.\n");
    system("cat system1.c");
    printf("-----------\nDone.\n");
    return 0;
}

三 编译运行

[root@localhost test]# g++ system1.c -o system1
[root@localhost test]# ./system1
running cat with system.
#include <stdlib.h>
#include <stdio.h>

int main()
{
    printf("running cat with system.\n");
    system("cat system1.c");
    printf("-----------\nDone.\n");
    return 0;
}
-----------
Done.

四 说明

其运行结果与sh -c "cat system1.c"类似。

[root@localhost test]# sh -c "cat system1.c"
#include <stdlib.h>
#include <stdio.h>

int main()
{
    printf("running cat with system.\n");
    system("cat system1.c");
    printf("-----------\nDone.\n");
    return 0;
}

其执行过程如下

1 fork一个子进程。

2 在子进程中调用exec函数去执行command。

3 在父进程中调用wait等待子进程结束。如果fork失败,system()函数返回-1。

system建立独立进程,拥有独立的代码空间,内存空间,等待新的进程执行完毕,system才返回.(阻塞)。

创建一个堵塞的新进程,新进程结束后,system才返回。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值