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!\n");
        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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值