linux c编程system与exec等区别简介
来源:互联网 发布:微信刷票软件免费版 编辑:程序博客网 时间:2024/06/07 20:42
//首先来看一个示例:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
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);
exit(0);
}
输出如下:
2012年 03月 17日 星期六 12:15:20 CST
exit status=0
sh: nosuchcommand: not found
exit status=32512
fanglin tty7 2012-03-17 08:57 (:0)
fanglin pts/0 2012-03-17 08:58 (:0.0)
exit status=11264
说明:
system函数调用来完成命令行的执行,而不直接用fork和exec,是因为system函数中进行了必须的错误处理和信号处理,更有利于编程。
在此,exec实现方法略过,有兴趣朋友可以试试用exec来实现看下效果。
system实际上还是fork+exec函数来执行外部程序,我伙来看现system的实现代码#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
int system(const char *cmdstring)
{
pid_t pid;
int status;
if(cmdstring==NULL){ return(1); }
if((pid=for())<0){ status=-1;
}else if(pid==0){
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
_exit(127); //不使用exit是为了保证进程的标准I/O流不被清掉
}else{
while(waitpid(pid, &status, 0)<0)
if(errno != EINTR){ status=-1; break; }
}
return(status);
}
- linux c编程system与exec等区别简介
- system与exec区别
- system与exec区别
- exec()与system()的区别
- PHP:exec与system区别
- exec()与system()的区别
- exec()与system()的区别
- system函数 与 exec函数的区别
- fork+exec 与system,popen区别
- Linux c编程 exec execl
- Linux c编程 exec execl
- PHP中exec、system等函数调用linux命令问题
- PHP中exec、system等函数调用linux命令问题
- PHP中exec、system等函数调用linux命令问题
- C语言中system和exec的本质区别
- C语言中system和exec的本质区别
- C语言中system和exec的本质区别
- fork/exec/system 用法简介
- double free *** set a breakpoint in malloc_error_break to debug
- SDL2.0版本变动后的一些改动
- 序列化
- iOS7 AVAudioRecorder不能录音
- Dynamic Performance Tables not accessible
- linux c编程system与exec等区别简介
- C/C++ 语言中的表达式求值
- 无需重编 修改程序的静态变量初始值
- 72 Android WebView AlertDialog
- 基于visual Studio2013解决算法导论之020单链表
- EDA技术课后题答案
- [Leetcode] Binary Tree Inorder Traversal (Java)
- oracle教程之oracle10g 手动创建数据详解(linux)
- PHP上台阶问题(斐波纳契数列应用)