intmain(int argc, char *argv[]) { printf("hello world (pid:%d)\n", (int) getpid()); int rc = fork(); if (rc < 0) { // fork failed; exit fprintf(stderr, "fork failed\n"); exit(1); } elseif (rc == 0) { // child (new process) printf("hello, I am child (pid:%d)\n", (int) getpid()); } else { // parent goes down this path (main) printf("hello, I am parent of %d (pid:%d)\n", rc, (int) getpid()); } return0; }
// 输出如下: // hello world (pid:29146) // hello, I am parent of 29147 (pid:29146) // hello, I am child (pid:29147) // 或者 // hello world (pid:29146) // hello, I am child (pid:29147) // hello, I am parent of 29147 (pid:29146)
过去某些系统采用协作(cooperative)方式来进行进程切换。在这种方式下,操作系统相信运行的进程会合理运行,进程会定期放弃 CPU,以便操作系统可以决定运行其他任务。 多数进程通过进行系统调用,将 CPU 的控制权转移给操作系统。也就是说在协作调度系统中,操作系统通过等待系统调用或某种非法操作发生,从而重新获得 CPU 的控制权。
抢占式多任务切换
如果没有硬件的额外帮助,如果进程拒绝进行系统调用也不出错,从而将控制权交还给操作系统,那么操作系统永远无法再次获得 CPU 的控制权。在协作式多任务切换中,当进程陷入无限循环时,唯一的办法就是重启。为了解决这个问题,就产生了抢占式(preemptive)方式进行进程切换。
如何在没有协作的情况下获得控制权呢,时钟中断(timer interrupt)可以解决这个棘手的问题。时钟设备可以编程为每隔几毫秒产生一次中断。产生中断时,当前正在运行的进程停止,操作系统中预先配置的中断处理程序(interrupt handler)会运行。此时,操作系统会重新获得 CPU 的控制权。