版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/88926811
一 点睛
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才返回。