每个系统调用的作用的一般细分:
fork:分叉当前进程。从字面上看,当调用 fork 时,执行会在调用 fork 时暂停,并将整个程序复制到作为原始进程的子进程空间的新进程空间中。然后,两个进程在 fork 调用之后立即继续并行执行。您需要获取 PID 才能判断当前正在执行的程序是子程序还是父程序。
exec:暂停当前进程的执行,用指定的新程序擦除内存中的当前进程以运行。然后它会运行新程序。
wait:挂起当前进程,直到至少一个子进程终止。它是 waitpid() 的包装,允许您暂停当前进程的执行并等待当前进程的子进程状态发生变化(可能是其自身的克隆或由exec)
下面是我在大学上的一门课中演示等待和分叉(但没有执行)的代码:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
const int BUFFER_SIZE = 1000;
void copySegment(int i, int segmentSize, FILE * fin, FILE * fout) {
// Does not need to be shown to prove point
}
int main(int argc, char * argv[]) {
int i;
sem_t * sem;
pid_t pid;
FILE * fin, * fout;
struct stat sbuf;
int fileSize, fileDescriptor, segmentSize;
fin = fopen(argv[1], "r");
fout = fopen("forkcopy.txt", "w");
fileDescriptor = fileno(fin);
fstat(fileDescriptor, &sbuf);
fileSize = sbuf.st_size;
segmentSize = fileSize / 4;
sem = sem_open("sem", O_CREAT | O_EXCL, 0644, 4);
sem_unlink("sem");
for (i = 0; i < 4; i++) {
pid = fork();
if (pid < 0)
printf("Fork error.\n");
else if (pid == 0)
break;
}
if (pid != 0) {
while (pid = waitpid(-1, NULL, 0)) {
if (errno == ECHILD)
break;
}
sem_destroy(sem);
fclose(fin);
fclose(fout);
exit(0);
} else {
sem_wait(sem);
copySegment(i, segmentSize, fin, fout);
sem_post(sem);
exit(0);
}
}