ที่นี่เราจะเห็นผลของการเรียกระบบ fork() และ exec() ใน C. ส้อมนี้ใช้เพื่อสร้างกระบวนการใหม่โดยการทำซ้ำกระบวนการเรียก กระบวนการใหม่เป็นกระบวนการลูก ดูคุณสมบัติต่อไปนี้
- โปรเซสลูกมี 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\n");
exit(EXIT_FAILURE);
} else if (process_id == 0) { //the child process is created
printf("The child process is (%u)\n",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)\n",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\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