system函数

NAME
       system - execute a shell command

SYNOPSIS
       #include <stdlib.h>

       int system(const char *command);
//运行程序的方法
./a.out
sh -c ./a.out
//Linux中的system源码(可以理解为封装的execl函数)
int system(const char * cmdstring)
{
        pid_t pid;
        int status;

        if(cmdstring == NULL){
      
                return (1);
        }


        if((pid = fork())<0){

                status = -1;
        }
        else if(pid == 0){
                execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
                -exit(127); //子进程正常执行则不会执行此语句
        }
        else{
                while(waitpid(pid, &status, 0) < 0){
                        if(errno != EINTER){
                                status = -1;
                                break;
                        }
                }
        }
        return status;
}

system()函数的返回值如下:
成功,则返回进程的状态值;当sh不能执行时,返回127;失败返回-1。

system是封装好的excel函数,但两者有区别:

//echoarg.c
#include <stdio.h>

int main(int argc,char **argv)
{
        int i = 0;
        for(i =  0;i < argc;i++){
                printf("argv[%d]:%s\n",i,argv[i]);
        }
        return 0;
}
//execl.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
        printf("before execl\n");
        if(execl("./echoarg","echoarg","abc",NULL) == -1)
        {
                printf("execl failed\n");
        }
        printf("after execl\n");
        return 0;
}

在这里插入图片描述

//system.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
        printf("before execl\n");
        if(system("./echoarg abc") == -1)
        {
                printf("execl failed\n");
        }
        printf("after execl\n");
        return 0;
}

在这里插入图片描述
通过对比可知:
system最终还会返回到原程序中,执行后面的代码;
execl不会返回到原程序中,因此不会执行后面的代码。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值