system函数
2015-11-26 11:21
579 查看
system函数
它一个和操作系统紧密相关的函数,用户可以使用它在自己的程序中调用系统提供的各种命令执行系统的命令行,其实也是调用程序创建一个进程来实现的。实际上,system函数的实现正是通过调用fork、exec、waitpid函数来完成的。system函数原型如下:
#include <stdlib.h> int system (const char *cmdstring);
由于system在其实现中调用了fork、exec、waitpid,因此有三种可能的返回值:
(1)如果fork失败或者waitpid返回除EINTR之外的出错,则system返回-1,而且errno中设置了错误类型 (2)如果exec失败(表示不能执行shell),则其返回值如同shell执行了exit(127)一样,即返回值为127 (3)否则所有三个函数(fork、exec和waitpid)都成功,并且system的返回值是shell的终止状态
system函数的使用时很方便的。
system()调用fork()产生子进程,由子进程来调用/bin/sh-c cmdstring来执行参数cmdstring字符串所代表的命令,此命令执行完后随即返回原调用的进程。在调用system()期间SIGCHLD信号会被暂时搁置,SIGINT和SIGQUIT信号则会被忽略
一个关于system函数调用的例子,cmd_system.c:
#include <stdlib.h> #include <stdio.h> int main(void) { int status; if((status = system(NULL)) < 0) { printf("system error!\n"); exit(0); } printf("exit status = %d\n",status); if((status = system("date")) < 0) { printf("system error!\n"); exit(0); } printf("exit status = %d\n",status); if((status = system("invalidcommand")) < 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; } 运行结果: hyx@hyx-virtual-machine:~/test$ ./cmd_system exit status = 1 2015年 11月 26日 星期四 10:24:08 CST exit status = 0 sh: 1: invalidcommand: not found exit status = 32512 hyx :0 2015-11-25 23:21 (:0) hyx pts/0 2015-11-25 23:22 (:0) exit status = 11264
相关文章推荐
- asp.net(C#)读取文件夹和子文件夹下所有文件,绑定到GRIDVIEW并排序 .
- 表达式语言--内置对象
- php如何遍历多维的stdClass Object 对象,php的转换成数组的函数只能转换外面一丛数组
- Erlang OTP源码分析 – gen_server
- 一个简单的端口扫描程序
- Linux---gdb调试
- iOS下的__block与__weak
- Groovy中的Actor模型_网页设计
- 《读书笔记》系列1:UNIX环境高级编程
- iOS微信支付
- Android开发之Intent.Action
- winform托盘时,要运行一个实例,解决办法
- 进程控制(四)
- scrollerView中嵌套了 RecyclerView ,RecyclerView高度变为零
- Macbook中的mysql密码忘记,如何修改
- Spring学习之IOC
- java Data、String、Long三种日期类型之间的相互转换
- Git 删除远程仓库文件
- 如何规划构建一套大型的Citrix桌面虚拟化架构 - Part2
- Java7新特性整理