Linux C编程--进程介绍5--system函数
来源:互联网 发布:ubuntu u盘 卡在启动 编辑:程序博客网 时间:2024/06/06 20:17
表头文件
#i nclude<stdlib.h>
定义函数
int system(const char * string);
这个函数是用fork,exec,waitpid这三个系统函数实现的,返回值相对比较复杂。
函数说明
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 来确认执行成功。对以返回值进行判断以验证system是否调用成功,其中用到的宏和wait函数的宏相同
附加说明
在编写具有SUID/SGID权限的程序时请勿使用system(),system()会继承环境变量,通过环境变量可能会造成系统安全的问题。
为了更好的理解system函数,下面给出函数的实现代码:
#include <sys/type.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 = fork())<0){status = -1;}else if(pid == 0){execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);-exit(127); //子进程正常执行则不会执行此语句}else{while(waitpid(pid, &status, 0) < 0){if(errno != EINTER){status = -1;break;}}}return status;}
下面给出一个简单的system函数调用程序
#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");exit(0);}printf("exit status =%d \n",status);if((status=system("who;exit "))<0){printf("system error");exit(0);}printf("exit status=%d\n",status);exit(0);}
- Linux C编程--进程介绍5--system函数
- linux c system函数介绍
- Linux C编程--进程介绍2--exec函数
- Linux C编程--进程介绍2--exec函数
- Linux C编程--进程介绍4--errno
- linux系统编程之进程(七):system()函数使用
- linux系统编程之进程(七):system()函数使用
- 进程编程中的system函数
- Linux C编程--进程介绍1--进程的创建
- Linux C编程--进程介绍3--进程终止和等待
- Linux C编程--进程介绍6--进程的各种标识
- Linux C编程--进程介绍3--进程终止和等待
- Linux C编程--进程介绍1--进程的创建
- Linux C编程--进程介绍3--进程终止和等待
- Linux C编程--进程间通信(IPC)5--System V IPC 机制1--消息队列
- Linux C编程--进程间通信(IPC)5--System V IPC 机制2--信号量
- Linux C编程--进程间通信(IPC)5--System V IPC 机制3--共享内存
- Linux C编程--进程间通信(IPC)5--System V IPC 机制1--消息队列
- Apache安装出现的问题的解决
- 教你去视频网站的开始广告
- Java中Xml解析详解 DOM、SAX、JDOM、DOM4J
- 2011级-csdn-java-张侃— struts2-上传功能
- Android_View,ViewGroup,Window之间的关系
- Linux C编程--进程介绍5--system函数
- 从Xcode编译时自带的“图片压缩”说起
- 进程及其进程环境
- The Bronte Story——3、The little books
- Java二维数组的三种表示形式
- git 代码协同之回车问题 CRLF LF
- Objective-C 词典对象(八)
- 2011级-csdn-java-张侃— Struts2——HelloWorld
- Objective-C 集合对象(九)