linux system函数使用详解 (zz from nodeadbird520)
相关函数
fork,execve,waitpid,popen
表头文件
#i nclude<stdlib.h>
定义函数
int system(const char * string);
函数说明
system()
会调用fork()产生子进程,由子进程来调用/bin/sh-c
string来执行参数string字符串所代表的命令,此命>令执行完后随即返回原调用的进程。在调用system()期间SIGCHLD
信号会被暂时搁置,SIGINT和SIGQUIT 信号则会被忽略。
返回值
=-1:出现错误
=0:调用成功但是没有出现子进程
>0:成功退出的子进程的id
如
果system()在调用/bin/sh时失败则返回127,其他失败原因返回-1。若参数string为空指针(NULL),则返回非零值>。
如果system()调用成功则最后会返回执行shell命令后的返回值,但是此返回值也有可能为
system()调用/bin/sh失败所返回的127,因此最好能再检查errno 来确认执行成功。
附加说明
在编写具有SUID/SGID权限的程序时请勿使用system(),system()会继承环境变量,通过环境变量可能会造成系统安全的问题。
范例
#i nclude<stdlib.h>
main()
{
system(“ls -al /etc/passwd /etc/shadow”);
}
执行结果:
-rw-r--r-- 1 root root 705 Sep 3 13 :52 /etc/passwd
-r--------- 1 root root 572 Sep 2 15 :34 /etc/shado
例2:
char tmp[];
sprintf(tmp,"/bin/mount -t vfat %s /mnt/usb",dev);
system(tmp);
其中dev是/dev/sda1。
system源码
#include
#include
#include
#include
int system(const char * cmdstring)
{
pid_t pid;
int status;
if(cmdstring == NULL){
return (1);
}
if((pid = fork())<0){
status = -1;
}
else if(pid == 0){
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
-exit(127); //子进程正常执行则不会执行此语句
}
else{
while(waitpid(pid, &sta
相关文档:
[/home/brimmer/src]$ ctags -R
"
-R"表示递归创建,也就包括源代码根目录下的所有子目录下的源程序。"
tags"文件中包括这些对象的列表:
l
用
#define定义的宏
l
枚举型变量的值
l  ......
1 红帽
rpm -ivh 安装
-e 删除
-u 升级
-q 查询
2 ubuntu
deb dpkg -i 安装
&n ......
/boot:这里存放的是启动LINUX时使用的一些核心文件。
/dev:dev是device(设备)的缩写。这个目录下是所有LINUX的外部设备,其功能类似DOS下的.sys和Win下的.vxd。在LINUX中设备和文件是用同种方法访问的。例如:/dev/hda代表第一个物理IDE硬盘。
/etc:这个目录用来存放所有的系统管理所需要的配置文件和子目录。
/bin:bin ......
fopen("/var/spool/cron/tmp","w+");
/////////////////////////////////////////
#i nclude <sys/types.h>
#i nclude <sys/stat.h>
#i nclude <fcntl.h>
#i nclude <unistd.h>
#i nclude <stdio.h>
#i nclude <string.h>
#i nclude <stdlib.h>
int main(){
in ......
gnome: 点右键---new Launcher,输入快捷方式的名称,并选择执行的程序即可。
kde: 右键单击桌面的空白处,在弹出的对话框中选“新建-应用程序链接”。再在弹出的窗口中点“执行”,在命令栏中点后面的浏览键,找到相应的程序。再点“常规”,进行取名、更改图标等操作,最后点确定,这样 ......