分别man system和 execl得到
——————————————————————————————————————————————————————————————
NAME
system - execute a shell commandwill be WEXITSTATUS(status). In case /bin/sh could not be executed,
the exit status will be that of a command that does exit(127).
If the value of command is NULL, system() returns nonzero if the shell
is available, and zero if not.
system() does not affect the wait status of any other children.
————————————————————————————————————————————————————————————————
NAME
execl, execlp, execle, execv, execvp, execvpe - execute a file
SYNOPSIS
#include <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg,
..., char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],
char *const envp[]);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
DESCRIPTION
The exec() family of functions replaces the current process image with
a new process image. The functions described in this manual page are
front-ends for execve(2). (See the manual page for execve(2) for fur‐
ther details about the replacement of the current process image.)
The initial argument for these functions is the name of a file that is
to be executed.
阅读完可以看出:
system是用shell来调用程序=fork+exec+waitpid,而exec是直接让你的程序代替用来的程序运行。
system 是在单独的进程中执行命令,完了还会回到你的程序中。而exec函数是直接在你的进程中执行新的程序,新的程序会把你的程序覆盖,除非调用出错,否则你再也回不到exec后面的代码,就是说你的程序就变成了exec调用的那个程序了。
看一下,下面的例子.
例子1
---------------------------------
system("your_program");
printf("You can see me! ");
---------------------------------
例子2
---------------------------------
exec("your_program");
printf("You can't see me! ");
---------------------------------
在例子1中,在你的程序执行完毕以后,会执行printf语句。
在例子2中,由于exec将程序your_program代替了本身,因此程序不再会执行printf语句。
在Linux下,exec通常会和fork语句一起用。
看下面的这个例子
--------------------------------------------
pid_t pid = fork();
if (pid < 0) {
printf(“fork error!”);
exit(-1);
} else if (pid == 0) {
//这里是子进程
printf("I'm son! ");
//执行其它的程序
exec("your_program");
} else {
//这里是父进程
printf("i'm father!");
wait();//等待子进程结束后返回
exit(0);
}