在这里,我们将看到在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<p>");
exit(EXIT_FAILURE);
} else if (process_id == 0) { //the child process is created
printf("The child process is (%u)</p><p>",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)</p><p>",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</p><p>");
else if (WIFEXITED(state) && WEXITSTATUS(state)) {
if (WEXITSTATUS(state) == 127) {
printf("Execution failed</p><p>");
} else
printf("program terminated with non-zero status</p><p>");
} else
printf("program didn't terminate normally</p><p>");
}
else {
printf("waitpid() function failed</p><p>");
}
exit(0);
}
return 0;
}</p>
输出
The parent process is (8627)
The child process is (8756)
program is executed successfully