
在这里,我们将看到在C语言中fork()和exec()系统调用的效果。fork用于通过复制调用进程来创建一个新的进程。新进程是子进程。请参考以下属性。
- 子进程有自己独特的进程ID。
- 子进程的父进程ID与调用进程的进程ID相同。
- 子进程不继承父进程的内存锁和信号量。
fork()返回子进程的PID。如果值非零,则为父进程的ID,如果值为0,则为子进程的ID。
exec()系统调用用于用新的进程映像替换当前进程映像。它将程序加载到当前空间,并从入口点运行。
因此,fork()和exec()之间的主要区别在于fork()启动了一个与主进程相同的新进程副本。exec()用新的进程映像替换当前进程映像,父进程和子进程同时执行。
立即学习“C语言免费学习笔记(深入)”;
示例
#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) { //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











