|
载入中... |
|
fork ( ) 作者 DreamChaser 日期 2009-7-16 2:13:00
The fork() system call will spawn a new child process which is an identical process to the parent except that has a new system process ID. The process is copied in memory from the parent and a new process structure is assigned by the kernel. The return value of the is which discriminates the two threads of execution. A zero is returned by the fork in the child's process. The environment, resource limits, umask, controlling terminal, current working directory, root directory, signal masks and other process resources are also duplicated from the parent in the forked child process.
Example: Compile: g++ -o ForkTest ForkTest.cpp Potential Pitfall]: Some memory duplicated by a forked process such as file pointers, will cause intermixed output from both processes. Use the wait() so that the processes do not access the file at the same time or open unique file deors. Some like stdout or stderr will be shared unless synchronized using wait() or some other mechanism. The file close on exit is another gotcha. A terminating process will close files before exiting. File locks set by the parent process are not inherited by the child process. [Potential Pitfall]: Race conditions can be created due to the unpredictability of when the kernel scheduler runs portions or time slices of the process. One can use wait(). the use of sleep() does not guarentee reliability of execution on a heavily loaded system as the scheduler behavior is not predictable by the application. Note on exit() vs _exit(): The C library exit() calls the kernel system call _exit() internally. The kernel system call_exit() will cause the kernel to close deors, free memory, and perform the kernel terminating process clean-up. The C library exit() call will flush I/O buffers and perform aditional clean-up before calling _exit() internally. The exit(status) causes the executable to return "status" as the return code for main(). When exit(status) is called by a child process, it allows the parent process to examine the terminating status of the child (if it terminates first). Without this call (or a call from main() to return()) and specifying the status argument, the process will not return a value. Man Pages:
|
载入中...
About Me载入中...
Category载入中...
newlog载入中...
Recent Comments载入中...
Recent Message载入中...
LinksSearch载入中...
Statistics载入中... |