子进程有自己独特的进程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
以上就是在c语言中,fork()和exec()之间的区别是什么?的详细内容。
