#include <errno.h> #include <signal.h> #include <unistd.h> int system (const char
*cmdstring)/* with appropriate signal handling * * pid_t pid;
int status;
struct Sigaction Ignore, saveintr, Savequit;
sigset_t Chldmask, Savemask; if (cmdstring = NULL) return (1); /* Always a command processor with UNIX */Ignore.sa_handler = sig_ign;
/* Ignore SIGINT and Sigquit * * Sigemptyset (&ignore.sa_mask);
ignore.sa_flags = 0;
if (Sigaction (SIGINT, &ignore, &saveintr) < 0) return (-1);
if (Sigaction (Sigquit, &ignore, &savequit) < 0) return (-1); Sigemptyset (&chldmask);
/* NOW block SIGCHLD * * Sigaddset (&chldmask, SIGCHLD);
if (Sigprocmask (Sig_block, &chldmask, &savemask) < 0) return (-1); if ((PID = fork ()) < 0) {
status =-1; /* Probably out of processes/else if (PID = 0) {/* Child//* Restore previous signal actions
& Reset Signal Mask * * sigaction (SIGINT, &saveintr, NULL);
Sigaction (Sigquit, &savequit, NULL);
Sigprocmask (Sig_setmask, &savemask, NULL);
Execl ("/bin/sh", "sh", "-C", Cmdstring, (char *) 0); _exit (127);
/* EXEC Error/else {/* Parent/while (Waitpid (PID, &status, 0) < 0)
if (errno!= eintr) {status =-1;/* error other than eintr from Waitpid () * *
Break }/* Restore previous signal actions & Reset Signal Mask */if (sigaction, SIGINT
TR, NULL) < 0) return (-1);
if (Sigaction (Sigquit, &savequit, NULL) < 0) return (-1); if (Sigprocmask (Sig_setmask, &savemask, NULL) < 0)
Return (-1);
return (status); }
System (execute shell command)
Related functions
Fork,execve,waitpid,popen
Table header File
#i nclude<stdlib.h>
Defining functions
int system (const char * string);
Function description
System () invokes the fork () to produce the child process, which invokes the/BIN/SH-C string to execute the command represented by the parameter string string, which then returns the process of the original call. The SIGCHLD signal is temporarily shelved during the call to System () and the SIGINT and sigquit signals are ignored.
return value
=-1: Error occurred
= 0: The call succeeded but no child processes appear
>0: ID of the child process that successfully exited
If system () fails while calling/bin/sh, 127 is returned, and the other failure reason returns-1. If the argument string is a null pointer (null), a value of not 0 > is returned.
If the system () call succeeds, the return value after executing the shell command is finally returned, but this return value is also likely to return 127 for system () call/bin/sh failure, so it is best to check errno again to confirm execution success.