system() 不用你自己去产生进程,它已经封装了,直接加入自己的命令
exec 需要你自己 fork 进程,然后exec 自己的命令
popen() 也可以实现执行你的命令,比system 开销小
1)system(shell命令或shell脚本路径);
例:在/tmp/testDir/目录下有shell脚本tsh.sh,内容为
#!/bin/sh
wget $1
echo "Done!"
wget $1
echo "Done!"
在同层目录下新建一个c文件
(以下代码 可带参数)
#include <stdio.h>
#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;
}
}
#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
[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内容如下:
#include<stdio.h>
main
{
FILE * fp;
charbuffer[80];
fp=popen(“~/myprogram/test.sh”,”r”);
fgets(buffer,sizeof(buffer),fp);
printf(“%s”,buffer);
pclose(fp);
}
main
{
FILE * fp;
charbuffer[80];
fp=popen(“~/myprogram/test.sh”,”r”);
fgets(buffer,sizeof(buffer),fp);
printf(“%s”,buffer);
pclose(fp);
}
履行 效果 如下:
运行输出
#include<stdio.h>
main
{
FILE * fp;
charbuffer[80];
fp=popen(“~/myprogram/test.sh”,”r”);
fgets(buffer,sizeof(buffer),fp);
printf(“%s”,buffer);
pclose(fp);
}
main
{
FILE * fp;
charbuffer[80];
fp=popen(“~/myprogram/test.sh”,”r”);
fgets(buffer,sizeof(buffer),fp);
printf(“%s”,buffer);
pclose(fp);
}
from :
http://blog.163.com/redhatroot@126/blog/static/1730563022010102911243458/
作部分修改