linux下system函数介绍

 

相关函数
        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。

 

#include #include #include #include #include #define MAJOR(a) (int)( (unsigned short) (a)>>8 ) #define MINOR(a) (int)( (unsigned short) (a)&0xFF ) int main(int argc, char** argv) { int status; if( (status = system("date")) < 0) { printf("system() error!/n"); exit(0); } printf("exit status = %d/n",status); if( (status = system("nosuchcommand")) < 0) { printf("system() error!/n"); exit(0); } printf("exit status = %d/n",status); if( (status = system("who; exit 44")) < 0) { printf("system() error!/n"); exit(0); } printf("exit status = %d/n",status); return 0; }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值