曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 5107|回复: 0
打印 上一主题 下一主题

[进程] system -- 启动一个新程序

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2009-6-14 23:36:21 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
函数原型
#include <stdlib.h>

int system ( const char  *string );

参数
命令字符串

说明:
执行参数字符串中给出的命令。如果 shell 无法启动这个命令,就返回 127;如果是其他错误就返回 -1;否则,system() 返回命令的退出代码。

下面比较两个代码
代码一
#include <stdlib.h>
#include <stdio.h>

int main()
{
    printf("Running ping with system\n");
    system("ping 192.168.2.1 &");
    printf("Done.\n");
   
    exit(0);
}
代码二:
#include <stdlib.h>
#include <stdio.h>

int main()
{
    printf("Running ping with system\n");
    system("ping 192.168.2.1");
    printf("Done.\n");
   
    exit(0);
}
代码一和代码二的区别是,代码一的 ping 命令在后台执行,代码二的 ping 命令则在前台执行。这样一来,代码二中 ping 命令会一直进行,也就是代码二程序不会退出,还句话说就是不会输出 Done 这个信息。而代码一则在启动 ping 命令后,程序输出 Done 信息就退出了,在代码二程序退出后,在终端中仍然可以见 ping 命令的输出结果。

一般来说,使用 system() 并不是启动其他进程的理想方法,因为它是通过 shell 来启动的。这样效率也不高,因为一个 shell 在一个程序启动之前开始,而 shell 却很依赖于 shell 的安装以及所使用的当前环境。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-4 20:15 , Processed in 0.077176 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表