C 中 fork() 和 exec() 的区别


这里我们来看看在 C 中 fork() 和 exec() 系统调用的效果。fork 用于通过复制调用进程来创建新进程。新进程为子进程。参见以下属性。

  • 子进程拥有自己唯一的进程 ID。
  • 子进程的父进程 ID 与调用进程的进程 ID 相同。
  • 子进程不会继承父进程的内存锁和信号量。

fork() 返回子进程的 PID。如果值为非零,则该值为父进程的 ID,如果为 0,则为子进程的 ID。

exec() 系统调用用于用新进程映像替换当前进程映像。它将程序加载到当前空间,并从入口点运行程序。

因此,fork() 和 exec() 之间的主要区别在于 fork 开始的新进程是主进程的副本。exec() 用新的进程映像替换当前进程映像,父进程和子进程同时执行。

示例

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
int main() {
   pid_t process_id;
   int return_val = 1;
   int state;
   process_id = fork();
   if (process_id == -1) { //when process id is negative, there is an error, unable to fork
      printf("can't fork, error occured
");          exit(EXIT_FAILURE);    } else if (process_id == 0) { //the child process is created       printf("The child process is (%u)
",getpid());          char * argv_list[] = {"ls","-lart","/home",NULL};       execv("ls",argv_list); // the execv() only return if error occured.       exit(0);    } else { //for the parent process       printf("The parent process is (%u)
",getppid());       if (waitpid(process_id, &state, 0) > 0) { //wait untill the process change its state          if (WIFEXITED(state) && !WEXITSTATUS(state))             printf("program is executed successfully
");          else if (WIFEXITED(state) && WEXITSTATUS(state)) {             if (WEXITSTATUS(state) == 127) {                printf("Execution failed
");             } else                printf("program terminated with non-zero status
");          } else             printf("program didn't terminate normally
");       }       else {          printf("waitpid() function failed
");       }       exit(0);    }    return 0; }

输出

The parent process is (8627)
The child process is (8756)
program is executed successfully

更新日期: 2019 年 7 月 30 日

3K+ 浏览量

开启你的 职业生涯

完成课程,获得证书

开始学习
广告
© . All rights reserved.