The code between if (child == 0) and the else statements is executed in the child
process. In particular, the child uses the execl() function call to execute the /bin/ls
program, which creates a directory listing of the current directory.
The waitpid() statement is executed in the parent process, which means that the parent
process will wait for the child process to terminate before continuing execution.
You can compile this program with the following command (if you have the GCC compiler
installed):
$ gcc forkexec.c -o forkexec
and then execute it like this:
$ ./forkexec
in parent
in child
28.doc a.out forkexec forkexec.c
Your output might be slightly different. The point to take away from this example is that Linux
makes it very easy to create new processes programmatically. Because it is so easy, it is a common
and powerful programming technique and a characteristic of the Linux programming model. Linux
is hardly alone in providing a mechanism by which one program can start another, but the
fork()/exec() technique is unique to Linux (and the UNIX systems on which Linux is based).
CPU and Memory Protection
Another fundamental component of programming on Linux systems is that the operating system
itself, which consists of the Linux kernel, is almost entirely insulated from all application programs.
Pages:
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370