Use shell in Linux applications

Source: Internet
Author: User

In Linux applications, there are many ways to call my shell (which is too powerful): fork (), exec * (), pipe, system () in this example, the system ()

It is very convenient to call. It is explained now.

# Include <stdlio. h>

# Include <stdlib. h>

Int main ()

{

System ("ifconfig eth0 10.17.28.1 ");

// System ("./ifconfig. Sh"); Use your script shell path.

Return 0;

}

// Certificate //------------------------------------------------------------------------------------------------------------------------------------------------------

Exec *

Method 2: exec () function family (convert)
Next let's take a look at how a process can start the execution of another program. Use the exec function family in Linux. The system calls execve () to replace the current process with a specified program. Its parameters include the file name (filename), the parameter list (argv), and the environment variable (envp ). Of course, there are more than one exec function family, but they are roughly the same. In Linux, they are: execl, execlp, execle, execv, execve, and execvp. Below I only take execlp as an example, what are the differences between other functions and execlp? Use the manexec command to learn about them.

Once a process calls the exec function, it is "dead". The system replaces the code segment with the code of the new program and discards the original data segment and stack segment, and allocate new data segments and stack segments for the new program. The only difference is the process number. That is to say, for the system, it is the same process, but it is already another program. (However, Some exec functions can inherit information such as environment variables .)

So what if my program wants to start the execution of another program but still wants to continue running? That is, combined with fork and exec. The following code starts other programs:

Char Command [256];

Void main ()

{

Int RTN;/* the return value of the sub-process */

While (1)

{

/* Read the command to be executed from the terminal */

Printf ("> ");

Fgets (command, 256, stdin );

Command [strlen (command)-1] = 0;

If (Fork () = 0)

{

/* The sub-process executes this command */

Execlp (command, command );

/* If the exec function returns, the command is not executed normally and the error message is printed */

Perror (command); exit (errorno );}

Else

{

/* Parent process. Wait until the child process ends and print the return value of the child process */

Wait (& RTN );

Printf ("child process return % d \ n",. RTN );

}

}

}

This program reads and executes commands from the terminal. After the execution is complete, the parent process continues to wait for the command to be read from the terminal. Anyone familiar with DOS and Windows system calls must know

DOS/Windows also have exec functions, which are used in a similar way, but dos/Windows also have spawn functions, because DOS is a single-task system, it can only "parent process" resident in the machine and then execute "child process", which is a function of the spawn class. Win32 is already a multi-task system, but it also retains the spawn class functions. The methods for implementing the spawn function in Win32 are similar to those in the preceding UNIX, after a sub-process is opened, the parent process continues to run after the sub-process ends. UNIX is a multi-task system at the beginning, so the spawn class functions are not required from the core point of view.

/Certificate /------------------------------------------------------------------------------------------------------------------------------------------------------

System is used to execute commands in a separate process. After the command is executed, it will return to your program.
While the exec function executes new programs directly in your process, and the new program overwrites your program. Unless an error occurs during the call, you will no longer be able to return the code after exec, that is to say, your program becomes the program called by Exec.

/Certificate /------------------------------------------------------------------------------------------------------------------------------------------------------

# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
Int main (INT argc, char * argv []) {
Char * envp [] = {"Path =/tmp", "user = lei", "status = testing", null };
Char * argv_execv [] = {"Echo", "excuted by execv", null };
Char * argv_execvp [] = {"Echo", "executed by execvp", null };
Char * argv_execve [] = {"env", null };
If (Fork () = 0 ){
If (execl ("/bin/echo", "Echo", "executed by execl", null) <0)
Perror ("Err on execl ");
}
If (Fork () = 0 ){
If (execlp ("Echo", "Echo", "executed by execlp", null) <0)
Perror ("Err on execlp ");
}
If (Fork () = 0 ){
If (execle ("/usr/bin/ENV", "env", null, envp) <0)
Perror ("Err on execle ");
}
If (Fork () = 0 ){
If (execv ("/bin/echo", argv_execv) <0)
Perror ("Err on execv ");
}
If (Fork () = 0 ){
If (execvp ("Echo", argv_execvp) <0)
Perror ("Err on execvp ");
}
If (Fork () = 0 ){
If (execve ("/usr/bin/ENV", argv_execve, envp) <0)
Perror ("Err on execve ");
}
Return 0;
}

/Certificate /------------------------------------------------------------------------------------------------------------------------------------------------------

The program calls two common Linux system commands, ECHO and Env. Echo will print out the command line parameters that follow, and env will be used to list all environment variables.
As the execution sequence of each sub-process cannot be controlled, a chaotic output may occur-the printed results of each sub-process may be mixed together, rather than strictly following the order listed in the program.
The most common errors:
In normal programming, if you use the exec function family, you must add an incorrect judgment statement. Compared with other system calls, exec is prone to injury, and the execution file location, permissions, and many other factors can cause the call to fail.
The most common errors are:
1) the file or path cannot be found, and errno is set to enoent;
2) If the array argv and envp forget to end with null, errno is set to efault;
3) You are not authorized to run the file to be executed. errno is set to eacces.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.