系统调用允许应用程序获得只有操作系统才有权限执行的服务。
系统调用(System Call)是操作系统提供的一组功能接口,给应用程序实现一系列高权限的功能服务。系统调用一般是实现整个计算机的核心资源的访问和管理功能。
system函数说明
system()会调用fork()产生子进程,复制进程映像(fork函数), 由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命令执行完后随即返回原调用的进程。在调用system()期间SIGCHLD 信号会被暂时搁置,SIGINT和SIGQUIT 信号则会被忽略。
所以,system直接会复制父进程的空间,这样在使用中,可能会因为资源问题,导致程序异常,特别是频繁调用system,会出现较高的概率异常。
为了解决这个问题,下面封装了一个system调用,来解决直接使用带来的问题,代码如下:
#define _CMD_LEN (512)
int _system (char *cmd);
static int _system (char *command)
{
int pid = 0;
int status = 0;
char *argv[4];
extern char **environ = NULL;
int ret = -1;
if (NULL == command) {
return -1;
}
pid = vfork(); /* vfork() also works */
if (pid < 0) {
return -1;
}
if (0 == pid) { /* child process */
close(pid);
argv[0] = "sh";
argv[1] = "-c";
argv[2] = command;
argv[3] = NULL;
ret = execve ("/bin/sh", argv, environ);
exit (127);
return ret;
}
/* wait for child process to start */
do
{
if (waitpid (pid, &status, 0) < 0) {
if (errno != EINTR) {
return status;
}
else {
return status;
}
}
} while (1);
return 0;
}
/*
代替系统调用system功能
*/
int fun_system_execve(const char *format, ...)
{
char execmdBuff[_CMD_LEN];
va_list vaList;
va_start (vaList, format);
vsnprintf ((char *)execmdBuff, sizeof(execmdBuff), format, vaList);
va_end (vaList);
return _system ((char *)execmdBuff);
}