C 中 fork() 和 exec() 的区别
这里我们将看到C中fork()和exec()系统调用的效果。fork用于通过复制调用进程来创建一个新进程。新进程是子进程。请参阅以下属性。
子进程有自己唯一的进程ID。
子进程的父进程id与调用进程的进程id相同。
子进程不继承父进程的内存锁和信号量。
在fork()返回子进程的PID。如果该值非零,那么它是父进程的id,如果它是0,那么这是子进程的id。
该exec()系统调用是用来与新的进程映像替换当前的进程映像。它将程序加载到当前空间,并从入口点运行它。
因此,fork()和之间的主要区别在于exec()fork启动新进程,它是主进程的副本。在exec()新的一个替换当前的进程映像,父母和子女有进程同时执行。
示例
#include输出结果#include #include #include #include #include int main() { pid_t process_id; int return_val = 1; int state; process_id = fork(); if (process_id == -1) { //进程id为负时,报错,无法fork printf("can't fork, error occured\n"); exit(EXIT_FAILURE); } else if (process_id == 0) { //子进程被创建 printf("The child process is (%u)\n",getpid()); char * argv_list[] = {"ls","-lart","/home",NULL}; execv("ls",argv_list); //execv()仅在发生错误时返回。 exit(0); } else { //对于父进程 printf("The parent process is (%u)\n",getppid()); if (waitpid(process_id, &state, 0) > 0) { //等到进程改变其状态 if (WIFEXITED(state) && !WEXITSTATUS(state)) printf("program is executed successfully\n"); else if (WIFEXITED(state) && WEXITSTATUS(state)) { if (WEXITSTATUS(state) == 127) { printf("Execution failed\n"); } else printf("program terminated with non-zero status\n"); } else printf("program didn't terminate normally\n"); } else { printf("waitpid() function failed\n"); } exit(0); } return 0; }
The parent process is (8627) The child process is (8756) program is executed successfully
热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特