Linux System Programming: Difference between revisions
Jump to navigation
Jump to search
(Created page with '== Reference == * [http://perl.plover.com/yak/commands-perl/samples/slide001.html System Programming in Perl: The Unix Process Model (slides)] == Process == A process contains: …') |
|||
Line 22: | Line 22: | ||
* Why '''fork and exec''' with 2 separate commands?<br/>Because the child process can alter its environment before it does the exec. For example:<br/><source lang="bash"> |
* Why '''fork and exec''' with 2 separate commands?<br/>Because the child process can alter its environment before it does the exec. For example:<br/><source lang="bash"> |
||
ps > /tmp/procs # The child shell will first change the output FD, without ps knowing |
ps > /tmp/procs # The child shell will first change the output FD, without ps knowing |
||
</source> |
|||
=== Fork === |
|||
* The ''child'' will get a '''new''' copy of the '''file descriptor (FD) table'''.<br/>So closing a file in the child will not interfere with the parents. |
|||
* However the '''system open file table''' is '''not''' copied; the same table is shared between child and parent. Why? Because parent must keep the same '''Seek pointer''' as the child: |
|||
<source lang="bash"> |
|||
cat ./pie |
|||
# #!/bin/sh |
|||
# echo "I like pie."; # Will move seek pointer, also in parent |
|||
# echo "Especially blackberry."; # Will write starting from new position of seek pointer! |
|||
./pie > piefile |
|||
</source> |
</source> |
Revision as of 13:26, 24 January 2011
Reference
Process
A process contains:
- A unique process ID number ('pid')
- A current working directory ('cwd')
- A user ID and group ID number (actually more than one of each)
- An open file table
- An environment' (just a bunch of string data)
- A signal table
- An alarm clock
- Lots of other equipment
Why fork & exec
- 2 main primitives of kernel to manage processes:
- fork: create a new process
- exec: replace a process's object code with the contents of a file
- Launching a new process is done in 2 steps:
- Fork the current process
- In the child process, exec the new file that will then replace the code of the current child but keep environment.
- Why fork and exec with 2 separate commands?
Because the child process can alter its environment before it does the exec. For example:ps > /tmp/procs # The child shell will first change the output FD, without ps knowing
Fork
- The child will get a new copy of the file descriptor (FD) table.
So closing a file in the child will not interfere with the parents. - However the system open file table is not copied; the same table is shared between child and parent. Why? Because parent must keep the same Seek pointer as the child:
cat ./pie
# #!/bin/sh
# echo "I like pie."; # Will move seek pointer, also in parent
# echo "Especially blackberry."; # Will write starting from new position of seek pointer!
./pie > piefile