Linux中的system函数的实现和解释
2013-04-18 19:26
267 查看
#include <sys/wait.h>
#include <errno.h> #include <signal.h> #include <unistd.h> int system(const char *cmdstring) /* with appropriate signal handling */ { pid_t pid; int status; struct sigaction ignore, saveintr, savequit; sigset_t chldmask, savemask; if (cmdstring == NULL) return(1); /* always a command processor with UNIX */ ignore.sa_handler = SIG_IGN; /* ignore SIGINT and SIGQUIT */ sigemptyset(&ignore.sa_mask); ignore.sa_flags = 0; if (sigaction(SIGINT, &ignore, &saveintr) < 0) return(-1); if (sigaction(SIGQUIT, &ignore, &savequit) < 0) return(-1); sigemptyset(&chldmask); /* now block SIGCHLD */ sigaddset(&chldmask, SIGCHLD); if (sigprocmask(SIG_BLOCK, &chldmask, &savemask) < 0) return(-1); if ((pid = fork()) < 0) { status = -1; /* probably out of processes */ } else if (pid == 0) { /* child */ /* restore previous signal actions & reset signal mask */ sigaction(SIGINT, &saveintr, NULL); sigaction(SIGQUIT, &savequit, NULL); sigprocmask(SIG_SETMASK, &savemask, NULL); execl("/bin/sh", "sh", "-c", cmdstring, (char *)0); _exit(127); /* exec error */ } else { /* parent */ while (waitpid(pid, &status, 0) < 0) if (errno != EINTR) { status = -1; /* error other than EINTR from waitpid() */ break; } } /* restore previous signal actions & reset signal mask */ if (sigaction(SIGINT, &saveintr, NULL) < 0) return(-1); if (sigaction(SIGQUIT, &savequit, NULL) < 0) return(-1); if (sigprocmask(SIG_SETMASK, &savemask, NULL) < 0) return(-1); return(status); }
system(执行shell 命令)
相关函数
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
来确认执行成功。
相关文章推荐
- Linux中的system函数的实现和解释
- Linux中的system函数的实现和解释
- Linux中的system函数的实现和解释
- 被调用的linux系统函数system的是如何实现的!
- linux 系统信号忽略和system函数返回值问题(system的实现)
- Linux下c++调用自己编写的matlab函数:通过shell script system command实现
- linux网络编程之System V 消息队列:消息队列实现回射客户/服务器和 msgsnd、msgrcv 函数
- LINUX中编写函数实现system功能
- 对于linux下system()函数的深度理解(整理)
- 检测按键(Linux中kbhit()函数的实现)
- 嵌入式linux的中断函数实现和分析
- linux 命令 system () 函数详解
- Linux下使用system()函数一定要谨慎
- Linux驱动总结3- unlocked_ioctl和堵塞(waitqueue)读写函数的实现
- opencv 中关于BOW模型的实现以及相关的函数解释
- 【C/C++】Linux下使用system()函数一定要谨慎
- Linux下使用system()函数一定要谨慎
- php执行linux系统命令的相关函数exec|system|popen
- [转]Linux 下给类tcp 通信模式的实现。select 函数
- 一些Linux用到的C工具集常用函数实现