Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 8.13 systemFunction 267


#include "apue.h"
#include <sys/wait.h>

int
main(void)
{
int status;

if ((status = system("date")) < 0)
err_sys("system() error");

pr_exit(status);

if ((status = system("nosuchcommand")) < 0)
err_sys("system() error");

pr_exit(status);

if ((status = system("who; exit 44")) < 0)
err_sys("system() error");

pr_exit(status);

exit(0);
}

Figure 8.23 Calling thesystemfunction

Earlier systems, including SVR3.2 and 4.3BSD, didn’t have thewaitpidfunction
available. Instead, the parent waited for the child, using a statement such as

while ((lastpid = wait(&status)) != pid && lastpid != -1)
;

Aproblem occurs if the process that callssystemhas spawned its own children before
callingsystem.Because thewhilestatement above keeps looping until the child that
was generated bysystemterminates, if any children of the process terminate beforethe
process identified bypid,then the process ID and termination status of these other
children arediscarded by thewhilestatement. Indeed, this inability towaitfor a
specific child is one of the reasons given in the POSIX.1 Rationale for including the
waitpidfunction. We’ll see in Section 15.3 that the same problem occurs with the
popenandpclosefunctions if the system doesn’t provide awaitpidfunction.

Set-User-ID Programs


What happens if we callsystemfrom a set-user-ID program? Doing so creates a
security hole and should never be attempted. Figure8.24 shows a simple program that
just callssystemfor its command-line argument.
Free download pdf