学习笔记——Linux下system()函数详解

system函数

system函数和exec函数一样,都是执行shell 命令,但是system比较顶,把execl函数封装起来,所以习惯上使用system函数

下面是手册的介绍

NAME
       system - execute a shell command//执行shell 命令

SYNOPSIS
       #include <stdlib.h>

       int system(const char *command);

DESCRIPTION
       system()  executes a command specified in command by calling /bin/sh -c
       command, and returns after the command has been completed.  During exe‐
       cution  of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT
       will be ignored.

接下来看看这个代码
参考:https://www.cnblogs.com/leijiangtao/p/4051387.html

先看linux版system函数的源码:
代码:

#include
#include
#include
#include

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,system中的execl接收并完成执行指令。
execl(“/bin/sh”, “sh”, “-c”, cmdstring, (char *)0);
这句话中sh -c是执行命令的前缀,和“./”一样,比如我们运行执行文件,第一种是./demo 还有一种是sh -c demo

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

我们随便应用一下上一节的demo

#include <stdio.h>
#include <unistd.h>

int main(int argc ,char **argv){
    
    
	
	
	if(system("date") == -1){
    
    
		printf("execl filed!\n");
		
		perror("becasue");
	}
	printf("system successful\n");
	return 0;
}

system 只需要传递一个命令参数,调用execl,执行起来应该是sh -c date
看下结果:
在这里插入图片描述

注意

system函数在执行成功之后会回到原来的点继续向下执行,这也就是为啥结果中有打印system successful

而execl函数是执行失败后回到原来的点继续向下执行
注意区分

猜你喜欢

转载自blog.csdn.net/qq_44333320/article/details/124869932