概述
下面为system函数的一种实现:
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
int system(const char *cmdstring)
{
pid_t
pid;
int
status;
if(cmdstring == NULL)
//system接受命令为空时直接返回
return(1);
if(pid = fork() < 0)
//fork一个子进程
{
status = -1;
}
else if(pid == 0)
//子进程启动一个程序来代替自己.
{
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
//调用shell,shell的路径是/bin/sh,剩下的为参数,-c选项告诉shell程序取下
_exit(127);
//一个命令行参数(在这里为cmdstring)作为命令输入.
}
else
{
while(waitpid(pid, &status, 0) < 0)
//父进程等待自进程结术.
{
if(errno != EINTR)
{
status = -1;
break;
}
}
}
return(status);
}
其中子进程相当于调用: /bin/sh -c cmdstring-----------为执行cmdstring命令.
最后
以上就是单身蛋挞为你收集整理的linux的system函数的全部内容,希望文章能够帮你解决linux的system函数所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复