1 .\" Copyright (C) Caldera International Inc. 2001-2002. All rights reserved.
3 .\" Redistribution and use in source and binary forms, with or without
4 .\" modification, are permitted provided that the following conditions are
7 .\" Redistributions of source code and documentation must retain the above
8 .\" copyright notice, this list of conditions and the following
11 .\" Redistributions in binary form must reproduce the above copyright
12 .\" notice, this list of conditions and the following disclaimer in the
13 .\" documentation and/or other materials provided with the distribution.
15 .\" All advertising materials mentioning features or use of this software
16 .\" must display the following acknowledgement:
18 .\" This product includes software developed or owned by Caldera
19 .\" International, Inc. Neither the name of Caldera International, Inc.
20 .\" nor the names of other contributors may be used to endorse or promote
21 .\" products derived from this software without specific prior written
24 .\" USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
25 .\" INTERNATIONAL, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
26 .\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
27 .\" WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28 .\" DISCLAIMED. IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE LIABLE
29 .\" FOR ANY DIRECT, INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
32 .\" BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
33 .\" WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
34 .\" OR OTHERWISE) RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
35 .\" IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 .\" @(#)p5 8.1 (Berkeley) 6/8/93
44 It is often easier to use a program written
45 by someone else than to invent one's own.
46 This section describes how to
47 execute a program from within another.
49 The ``System'' Function
51 The easiest way to execute a program from another
53 the standard library routine
56 takes one argument, a command string exactly as typed
58 (except for the newline at the end)
60 For instance, to time-stamp the output of a program,
65 /* rest of processing */
68 If the command string has to be built from pieces,
69 the in-memory formatting capabilities of
77 normally buffer their input;
78 terminal I/O will not be properly synchronized unless
79 this buffering is defeated.
86 Low-Level Process Creation \(em Execl and Execv
88 If you're not using the standard library,
89 or if you need finer control over what
91 you will have to construct calls to other programs
92 using the more primitive routines that the standard
97 The most basic operation is to execute another program
103 To print the date as the last action of a running program,
106 execl("/bin/date", "date", NULL);
108 The first argument to
113 of the command; you have to know where it is found
115 The second argument is conventionally
117 (that is, the last component of the file name),
118 but this is seldom used except as a place-holder.
119 If the command takes arguments, they are strung out after
121 the end of the list is marked by a
128 overlays the existing program with
130 runs that, then exits.
134 return to the original program.
137 a program might fall into two or more phases
138 that communicate only through temporary files.
139 Here it is natural to make the second pass
144 The one exception to the rule that the original program never gets control
145 back occurs when there is an error, for example if the file can't be found
146 or is not executable.
147 If you don't know where
151 execl("/bin/date", "date", NULL);
152 execl("/usr/bin/date", "date", NULL);
153 fprintf(stderr, "Someone stole 'date'\en");
160 is useful when you don't know in advance how many arguments there are going to be.
163 execv(filename, argp);
167 is an array of pointers to the arguments;
168 the last pointer in the array must be
172 can tell where the list ends.
176 is the file in which the program is found, and
178 is the name of the program.
179 (This arrangement is identical to the
181 array for program arguments.)
183 Neither of these routines provides the niceties of normal command execution.
184 There is no automatic search of multiple directories \(em
185 you have to know precisely where the command is located.
186 Nor do you get the expansion of metacharacters like
193 in the argument list.
194 If you want these, use
198 which then does all the work.
201 that contains the complete command as it would have been typed
202 at the terminal, then say
204 execl("/bin/sh", "sh", "-c", commandline, NULL);
206 The shell is assumed to be at a fixed place,
210 says to treat the next argument
211 as a whole command line, so it does just what you want.
212 The only problem is in constructing the right information
216 Control of Processes \(em Fork and Wait
218 So far what we've talked about isn't really all that useful by itself.
219 Now we will show how to regain control after running
224 Since these routines simply overlay the new program on the old one,
225 to save the old one requires that it first be split into
227 one of these can be overlaid, while the other waits for the new,
228 overlaying program to finish.
229 The splitting is done by a routine called
234 splits the program into two copies, both of which continue to run.
235 The only difference between the two is the value of
238 In one of these processes (the ``child''),
244 is non-zero; it is the process number of the child.
245 Thus the basic way to call, and return from,
249 execl("/bin/sh", "sh", "-c", cmd, NULL); /* in child */
251 And in fact, except for handling errors, this is sufficient.
254 makes two copies of the program.
255 In the child, the value returned by
267 (If there is any error,
272 More often, the parent wants to wait for the child to terminate
273 before continuing itself.
274 This can be done with
284 This still doesn't handle any abnormal conditions, such as a failure
289 or the possibility that there might be more than one child running simultaneously.
294 of the terminated child, if you want to check it against the value
297 Finally, this fragment doesn't deal with any
298 funny behavior on the part of the child
299 (which is reported in
301 Still, these three lines
302 are the heart of the standard library's
305 which we'll show in a moment.
311 encodes in its low-order eight bits
312 the system's idea of the child's termination status;
313 it is 0 for normal termination and non-zero to indicate
314 various kinds of problems.
315 The next higher eight bits are taken from the argument
318 which caused a normal termination of the child process.
319 It is good coding practice
320 for all programs to return meaningful
323 When a program is called by the shell,
324 the three file descriptors
325 0, 1, and 2 are set up pointing at the right files,
326 and all other possible file descriptors
327 are available for use.
328 When this program calls another one,
329 correct etiquette suggests making sure the same conditions
335 calls affects open files in any way.
336 If the parent is buffering output
337 that must come out before output from the child,
338 the parent must flush its buffers
342 if a caller buffers an input stream,
343 the called program will lose any information
344 that has been read by the caller.
351 is an I/O channel intended for use
352 between two cooperating processes:
353 one process writes into the pipe,
354 while the other reads.
355 The system looks after buffering the data and synchronizing
357 Most pipes are created by the shell,
362 which connects the standard output of
364 to the standard input of
366 Sometimes, however, it is most convenient
367 for a process to set up its own plumbing;
368 in this section, we will illustrate how
369 the pipe connection is established and used.
374 Since a pipe is used for both reading and writing,
375 two file descriptors are returned;
376 the actual usage is like this:
382 /* there was an error ... */
385 is an array of two file descriptors, where
387 is the read side of the pipe and
395 calls just like any other file descriptors.
397 If a process reads a pipe which is empty,
398 it will wait until data arrives;
399 if a process writes into a pipe which
400 is too full, it will wait until the pipe empties somewhat.
401 If the write side of the pipe is closed,
404 will encounter end of file.
406 To illustrate the use of pipes in a realistic setting,
407 let us write a function called
408 .UL popen(cmd,\ mode) ,
409 which creates a process
414 and returns a file descriptor that will either
415 read or write that process, according to
420 fout = popen("pr", WRITE);
422 creates a process that executes
428 calls using the file descriptor
430 will send their data to that process
440 to create two copies of itself.
441 The child decides whether it is supposed to read or write,
442 closes the other side of the pipe,
443 then calls the shell (via
445 to run the desired process.
446 The parent likewise closes the end of the pipe it does not use.
447 These closes are necessary to make end-of-file tests work properly.
448 For example, if a child that intends to read
449 fails to close the write end of the pipe, it will never
450 see the end of the pipe file, just because there is one writer
457 #define tst(a, b) (mode == READ ? (b) : (a))
458 static int popen_pid;
468 if ((popen_pid = fork()) == 0) {
469 close(tst(p[WRITE], p[READ]));
471 dup(tst(p[READ], p[WRITE]));
472 close(tst(p[READ], p[WRITE]));
473 execl("/bin/sh", "sh", "-c", cmd, 0);
474 _exit(1); /* disaster has occurred if we get here */
478 close(tst(p[READ], p[WRITE]));
479 return(tst(p[WRITE], p[READ]));
487 that the task is to create a child process that will read data from the parent.
490 closes the write side of the pipe,
491 leaving the read side open.
495 dup(tst(p[READ], p[WRITE]));
497 are the conventional way to associate the pipe descriptor
498 with the standard input of the child.
501 closes file descriptor 0,
502 that is, the standard input.
504 is a system call that
505 returns a duplicate of an already open file descriptor.
506 File descriptors are assigned in increasing order
507 and the first available one is returned,
511 is to copy the file descriptor for the pipe (read side)
512 to file descriptor 0;
513 thus the read side of the pipe becomes the standard input.
514 (Yes, this is a bit tricky, but it's a standard idiom.)
515 Finally, the old read side of the pipe is closed.
517 A similar sequence of operations takes place
518 when the child process is supposed to write
519 from the parent instead of reading.
520 You may find it a useful exercise to step through that case.
522 The job is not quite done,
523 for we still need a function
525 to close the pipe created by
527 The main reason for using a separate function rather than
529 is that it is desirable to wait for the termination of the child process.
530 First, the return value from
532 indicates whether the process succeeded.
533 Equally important when a process creates several children
534 is that only a bounded number of unwaited-for children
535 can exist, even if some of them have terminated;
538 lays the child to rest.
543 pclose(fd) /* close pipe fd */
546 register r, (*hstat)(), (*istat)(), (*qstat)();
548 extern int popen_pid;
551 istat = signal(SIGINT, SIG_IGN);
552 qstat = signal(SIGQUIT, SIG_IGN);
553 hstat = signal(SIGHUP, SIG_IGN);
554 while ((r = wait(&status)) != popen_pid && r != -1);
557 signal(SIGINT, istat);
558 signal(SIGQUIT, qstat);
559 signal(SIGHUP, hstat);
565 make sure that no interrupts, etc.,
566 interfere with the waiting process;
567 this is the topic of the next section.
569 The routine as written has the limitation that only one pipe may
570 be open at once, because of the single shared variable
572 it really should be an array indexed by file descriptor.
575 function, with slightly different arguments and return value is available
576 as part of the standard I/O library discussed below.
577 As currently written, it shares the same limitation.