#include <stdlib.h> int system(const char *command);
execl("/bin/sh", "sh", "-c", command, (char *) NULL);
system() が返るのはコマンドが完了した後である。
コマンドの実行中は、 system() を呼び出したプロセスでは、 SIGCHLD はブロックされ、 SIGINT と SIGQUIT は無視される (command を実行する子プロセスでは、これらのシグナルはデフォルトの処理方法にしたがって処理される)。
command が NULL の場合、 system() はそのシステムでシェルが利用可能かを示すステータスを返す。
最後の 2 つの場合、返り値は "wait status" であり、 waitpid(2) に書かれているマクロ (つまり WIFEXITED() や WEXITSTATUS() などのマクロ) を使って検査することができる。
system() は他の子プロセスのウエイトステータスには影響を与えない。
| インターフェース | 属性 | 値 |
| system() | Thread safety | MT-Safe |
(「どの」ヘッダーファイルをインクルードするよりも前に) 機能検査マクロ _XOPEN_SOURCE が定義された場合には、 waitpid(2) で説明されているマクロ群 (WEXITSTATUS() 等) が <stdlib.h> をインクルードすると利用可能になる。
既に述べたように、 system() は SIGINT と SIGQUIT を無視する。 よってループから system() を呼ぶプログラムは、 以下の例のように子プロセスの終了状態を自分でチェックしておかないと、 中断できなくなるかもしれない。
while (something) {
int ret = system("foo");
if (WIFSIGNALED(ret) &&
(WTERMSIG(ret) == SIGINT || WTERMSIG(ret) == SIGQUIT))
break;
}
According to POSIX.1, it is unspecified whether handlers registered using pthread_atfork(3) are called during the execution of system(). In the glibc implementation, such handlers are not called.
Before glibc 2.1.3, the check for the availability of /bin/sh was not actually performed if command was NULL; instead it was always assumed to be available, and system() always returned 1 in this case. Since glibc 2.1.3, this check is performed because, even though POSIX.1-2001 requires a conforming implementation to provide a shell, that shell may not be available or executable if the calling program has previously called chroot(2) (which is not specified by POSIX.1-2001).
シェルコマンドがステータス 127 で終了することもある。 この場合、system() の返り値は、子プロセスでシェルが実行できなかった場合と区別できない。
system() will not, in fact, work properly from programs with set-user-ID or set-group-ID privileges on systems on which /bin/sh is bash version 2: as a security measure, bash 2 drops privileges on startup. (Debian uses a different shell, dash(1), which does not do this when invoked as sh.)
Any user input that is employed as part of command should be carefully sanitized, to ensure that unexpected shell commands or command options are not executed. Such risks are especially grave when using system() from a privileged program.
system(" -unfortunate-command-name");