system() 不用你自己去产生进程,它已经封装了,直接加入自己的命令
exec 需要你自己 fork 进程,然后exec 自己的命令
popen() 也可以实现执行你的命令,比system 开销小
1)system(shell命令或shell脚本路径);
例:在/tmp/testDir/目录下有shell脚本tsh.sh,内容为
wget $ 1
echo " Done! "
在同层目录下新建一个c文件
(以下代码 可带参数)
#include < string .h >
#include < unistd.h >
int main( int argc , char * argv[])
{
char arg[ 300 ] = " /tmp/testDir/tsh.sh " ;
if ( argv[ 1 ] != NULL )
{
strcat(arg,argv[ 1 ]);
system(arg);
printf( " \ndone message in program\n " );
return 1 ;
}
else
{
printf( " Error: Empty input\n " );
return 0 ;
}
}
履行 效果 如下:
[root@localhost testDir]#gcc call_exec1.c - o call_exec1
[root@localhost testDir]#. / call_exec1 http: // www.baidu.com/img/logo-yy.gif
-- 2011 - 01 - 21 17 : 02 : 22 -- http: // www.baidu.com/img/logo-yy.gif
正在解析主机 www.baidu.com... 61.135 . 169.105 , 61.135 . 169.125
Connecting to www.baidu.com | 61.135 . 169.105 | : 80 ... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度: 1618 ( 1 .6K) [image / gif]
Saving to: `logo - yy.gif '
100 % [ ======================================> ] 1 , 618 -- . - K / s in 0 .001s
2011 - 01 - 21 17 : 02 : 34 ( 3.05 MB / s) - `logo - yy.gif ' saved [1618/1618]
Done !
done message in program
2)popen(char *command,char *type)
例:C程序popentest.c内容如下:
main
{
FILE * fp;
charbuffer[ 80 ];
fp = popen(“ ~/ myprogram / test.sh”,”r”);
fgets(buffer, sizeof (buffer),fp);
printf(“ % s”,buffer);
pclose(fp);
}
http://www.cnblogs.com/no7dw/archive/2011/01/22/1941858.html
另外一个博客的内容,system可以直接执行命令。
先在root下vim tsh.sh,写入以下内容
#!/bin/sh
echo "Make Dir Start!"
mkdir -p /root/tsh
mkdir -p /root/tsh/test1
mkdir -p /root/tsh/test2
mkdir -p /root/tsh/test3
mkdir -p /root/tsh/test4
echo "Make Dir Done!"
再在root下vim test.c,写入以下内容
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc ,char *argv[])
{
system("/root/tsh.sh");
system("mkdir -p /root/tsh/test5");
printf("\nDone message in program!\n");
return 1;
}
在终端编译test.c,gcc test.c -o test,产生test可执行文件
在终端执行./test,可得到如下结果
Make Dir Start!
Make Dir Done!
Done message in program!
同时在root下创建了tsh目录,并在其下分别创建了test1、test2、test3、test4、test5这几个目录
如下方法也可以执行脚本
#include <stdio.h>
int main(void)
{
FILE *fp;
char buffer[200];
fp=popen("/root/tsh.sh","r");
fgets(buffer,sizeof(buffer),fp);
printf("%s",buffer);
pclose(fp);
return 0;
}
执行后能创建以上的那些文件夹(test5文件夹无法创建,因为脚本只创建了test1-----test4)。
不过程序有些问题,但是只能打印出
Make Dir Start!
后两句无法打印出,应该是读文件到buffer只读了一次,所以只能显示第一个,具体解决办法待研究
http://blog.163.com/allegro_tyc/blog/static/337437682011616101931854/