C 中的 fork();哪个应该是父进程哪个应该是子进程

fork() in C; which should be parent process which should be child process

这似乎是一个愚蠢的问题,但除了知道这是关于多线程之外,我对 fork() 并没有很好的理解。子进程就像一个线程。如果任务需要通过fork()处理,如何正确分配任务给父进程和子进程?

检查 fork 的 return 值。 child 进程将收到 0 的值。 parent 将接收 child.

的进程 ID 的值

阅读 Advanced Linux Programming,其中有一整章专门介绍过程(因为 fork 很难解释);

然后阅读 fork(2); fork is not about multi-threading, but about creating processes. Threads are generally created with pthread_create(3) (which is implemented above clone(2), a Linux specific syscall). Read some pthreads tutorial 的文档以了解有关线程的更多信息。

PS。 fork难以理解(您需要数小时的阅读、一些实验,也许使用 strace(1), till you reach the "AhAh" insight moment when you have understood it) since it returns twice on success. You need to keep its result, and you need to test the result for the three cases : <0 (failure), ==0 (child), >0 (parent). Don't forget to later call waitpid(2) (or something similar) in the parent, to avoid having zombie processes