Linux system函数详解

system
功能:system()函数调用"/bin/sh -c command"执行特定的命令,阻塞当前进程直到command命令执行完毕
原型
    int system(const char *command);
返回值:
    如果无法启动shell运行命令,system将返回127;出现不能执行system调用的其他错误时返回-1。如果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!
");
        return -1;
    }
    pid_t pid = 0;
    int status=0;
    pid = fork();
    if (pid < 0)
    {
        status=-1;
    }
    if(pid==0)
    {
        //执行shell命令
        execle("/bin/sh","sh","-c",command,NULL,NULL);
        exit(127);
    }else if(pid>0)
    {
        //先执行一次waitpid,但是要处理阻塞中的信号中断
        while(waitpid(pid,&status,0)<0)
        {
            if(errno==EINTR)
                //如果是信号中断,应该一直执行一次waitpid,直到等待子进程返回
                continue;
            //发现不是信号中断,导致waitpid返回-1,直接退出,表明此时父进程已经成功接收到子进程的pid
            //特别注明:执行到这里,说明waitpid已经执行失败,如果能成功接收到子进程的pid,应该不会进入while循环
            status=-1;
            break;
        }
    }
    return status;
}

int main(int arg, char *args[])
{
    char buf[1024]={0};
    read(STDIN_FILENO,buf,sizeof(buf));
    my_system(buf);
    return 0;
}
原文地址:https://www.cnblogs.com/zhanggaofeng/p/6074152.html