曲径通幽论坛

标题: system -- 启动一个新程序 [打印本页]

作者: beyes    时间: 2009-6-14 23:36
标题: system -- 启动一个新程序
函数原型
#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 的安装以及所使用的当前环境。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2