fork() and wait() calls

夙愿已清 提交于 2019-12-03 20:15:05

Fork makes a new process, which can execute simultaneously (or interleaved) with the parent process. It does not make the parent process stop. After the fork call, both processes are "runnable", and it is quite possible that both of them are running. If the parent process is lucky, it will be the first one to be able to output. In general, it is unpredictable.

There are a number of bugs in that code, so I wouldn't treat it as a good source of learning how to use fork().

For example, the parent process uses printf to write the messages:

*** Parent is about to fork process 1 ***
*** Parent is about to fork process 2 ***

However, it is quite possible that stdout is not line-buffered (for example, it might be redirected.) In that case, the output will only be copied into the in-memory output buffer, and will be printed to stdout when the buffer fills up or the stdout file descriptor is closed. However, the children will be forked with the same in-memory output buffer, so both the parent and child one will output the *** Parent is about to fork process 1 *** message and all three processes will output the *** Parent is about to fork process 2 *** message.

Also, if the stdout is redirected to a seekable stream not opened in append mode, then each process's file descriptor 1 will have an associated file position which each will manipulate independently. That may result in the two child processes overwriting each other's output. (On my system, the overwriting happens about 80% of the time.)

On a non-busy multicore or multiprocessor system, it is highly likely that the children began executing almost instantly. On Unix and Linux, forking is a fast and easy operation: copy some memory descriptors, duplicate some resources, fix up some signal logic and leave both processes runnable. The scheduler is not predictable (at this level of observation): it is designed to be fair and equitable.

Besides, what the children do is more computationally heavy—formatting text, buffering it in the CRTL, possibly transferring it to the i/o system—than what the parent does: fork(), compare a number, wait().

So it is not surprising that the parent quickly gets to its wait() at which point it is no longer competing for CPU time.

Following each printf() with a fflush(stdout) might (or might not) improve consistency by removing two levels of i/o buffering from the mix.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!