Linux system函数详解

时间:2021-05-07 20:50:15
system
功能:system()函数调用"/bin/sh -c command"执行特定的命令,阻塞当前进程直到command命令执行完毕
原型
int system(const char *command);
返回值:
如果无法启动shell运行命令,system将返回127;出现不能执行system调用的其他错误时返回-。如果systenm能够顺利执行,返回那个命令的退出码
system函数执行时,内部会调用fork,execve,waitpid等函数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h> //自己实现system函数
int my_system(const char * command)
{
if(command==NULL)
{
printf("command not allow null!\n");
return -;
}
pid_t pid = ;
int status=;
pid = fork();
if (pid < )
{
status=-;
}
if(pid==)
{
//执行shell命令
execle("/bin/sh","sh","-c",command,NULL,NULL);
exit();
}else if(pid>)
{
//先执行一次waitpid,但是要处理阻塞中的信号中断
while(waitpid(pid,&status,)<)
{
if(errno==EINTR)
//如果是信号中断,应该一直执行一次waitpid,直到等待子进程返回
continue;
//发现不是信号中断,导致waitpid返回-1,直接退出,表明此时父进程已经成功接收到子进程的pid
//特别注明:执行到这里,说明waitpid已经执行失败,如果能成功接收到子进程的pid,应该不会进入while循环
status=-;
break;
}
}
return status;
} int main(int arg, char *args[])
{
char buf[]={};
read(STDIN_FILENO,buf,sizeof(buf));
my_system(buf);
return ;
}