本文共 1380 字,大约阅读时间需要 4 分钟。
fork()是用于建立进程的手段之一,但是fork()只能建立相同程序的副本。
Linux系统还提供了系统调用exec系列。它可用于新程序的运行。
如果exec调用成功,调用进程将被覆盖,然后从新程序的入口开始执行。这样就产生了一个新的进程,但是它的进程标识符与调用进程相同。这就是说,exec没有建立一个与调用进程并发的新进程,而是用新进程取代了原来的进程。所以,对exec调用成功后,没有任何数据返回,这与fork()不同。
下面给出了exec系列调用在Linux系统中unistd.h中的函数声明:
int execl(const char *path, const *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[]);
下面来看一个exec函数的示例:
#include#include int main(){ printf("Executing ls\n"); execl("/bin/ls", "ls", "-la", NULL); printf("------End of execl()\n"); // 输出了下面的语句就表明execl调用失败了 perror("execl failed to run ls"); return 0;}
运行结果:
liuyuhai@YeeDev-Server:~/work_test$ ./a.outExecuting lstotal 32drwxrwxr-x 2 liuyuhai liuyuhai 4096 Jan 2 16:07 .drwxr-xr-x 36 liuyuhai liuyuhai 4096 Jan 2 15:57 ..-rwxrwxr-x 1 liuyuhai liuyuhai 8704 Jan 2 16:07 a.out-rw-r--r-- 1 liuyuhai liuyuhai 0 Dec 23 16:19 bar-rwxrwxr-x 1 liuyuhai liuyuhai 0 Dec 23 09:39 file-rw-rwSrw- 1 liuyuhai liuyuhai 0 Dec 23 16:19 foo-rw-rw-r-- 1 liuyuhai liuyuhai 6968 Jan 2 16:07 test1.c-rw-rw-r-- 1 liuyuhai liuyuhai 1117 Dec 30 19:06 test.cliuyuhai@YeeDev-Server:~/work_test$
注: “printf("------End of execl()\n"); “没有输出噢。这正好说明了:exec没有建立一个与调用进程并发的新进程,而是用新进程取代了原来的进程。
转载地址:http://roldi.baihongyu.com/