C language to call shell command _ Exec

Source: Internet
Author: User
Tags call shell

Method 1: # include <stdlib. h> INT system (const char * string );
Method 2: exec () function family
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;/* value returned by 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, print the error message */perror (command); exit (errorno);} else {/* parent process. Wait until the child process ends, and print the sub-process return value */Wait (& RTN); printf ("child process return % D/N ",. RTN) ;}} the program reads the command from the terminal and runs it. After the execution is complete, the parent process continues to wait for the command to be read from the terminal. If you are familiar with DOS and Windows system calls, you must know that DOS/Windows also has exec functions. The usage is similar, but dos/Windows also has spawn functions, because DOS is a single-task system, it can only "parent process" resident in the machine and then execute "sub-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.

Bytes ---------------------------------------------------------------------------------------------------------

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.

Bytes -------------------------------------------------------------------------------------------------------

/*
* Exec_test_main.c
*
* Created on: 2010-9-8
* Author: Kerwin
*/

/* Exec. C */
# 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;
}
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.

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.