Study notes - detailed explanation of system() function under Linux

system function

The system function is the same as the exec function, which executes shell commands, but the system is the top and encapsulates the execl function, so it is customary to use the system function

The following is an introduction to the manual

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.

Next, look at this code
Reference: 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;
}

That is, we pass the parameter system, and the execl in the system receives and completes the execution instruction.
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
In this sentence, sh -c is the prefix of the execution command, which is the same as "./". For example, we run Execution files, the first one is ./demo and the other one is sh -c demo

The return value of the system() function is as follows:
if successful, it will return the status value of the process;
when sh cannot be executed, it will return 127;
if it fails, it will return -1;

Let's apply the demo in the previous section casually

#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 only needs to pass a command parameter to call execl, and the execution should be sh -c date
to see the result:
insert image description here

Notice

After the system function is successfully executed, it will return to the original point and continue to execute downwards, which is why the system successful is printed in the result

The execl function returns to the original point after the execution fails and continues to execute downwards. Pay
attention to the distinction

Guess you like

Origin blog.csdn.net/qq_44333320/article/details/124869932