Posted on 2010-11-01 17:46
Prayer 閱讀(5547)
評論(0) 編輯 收藏 引用 所屬分類:
C/C++ 、
LINUX/UNIX/AIX
system(執行shell 命令)
相關函數 fork,execve,waitpid,popen
表頭文件 #include<stdlib.h>
定義函數 int system(const char * string);
函數說明 system()會調用fork()產生子進程,由子進程來調用/bin/sh-c string來執行參數string字符串所代表的命令,此命令執行完后隨即返回原調用的進程。在調用system()期間SIGCHLD 信號會被暫時擱置,SIGINT和SIGQUIT 信號則會被忽略。
返回值 如果system()在調用/bin/sh時失敗則返回127,其他失敗原因返回-1。若參數string為空指針(NULL),則返回非零值。如果system()調用成功則最后會返回執行shell命令后的返回值,但是此返回值也有可能為system()調用/bin/sh失敗所返回的127,因此最好能再檢查errno 來確認執行成功。
附加說明 在編寫具有SUID/SGID權限的程序時請勿使用system(),system()會繼承環境變量,通過環境變量可能會造成系統安全的問題。
范例 #include<stdlib.h>
main()
{
system(“ls -al /etc/passwd /etc/shadow”);
}
執行 -rw-r--r-- 1 root root 705 Sep 3 13 :52 /etc/passwd
-r--------- 1 root root 572 Sep 2 15 :34 /etc/shadow
Upon successful completion, the system subroutine returns the exit status of the shell. The exit status of the shell
is returned in the same manner as a call to the wait or waitpid subroutine, using the structures in the sys/wait.h
file.
If the String parameter is a null pointer and a command processor is available, the system subroutine returns a
nonzero value. If the fork subroutine fails or if the exit status of the shell cannot be obtained, the system
subroutine returns a value of -1. If the exec l subroutine fails, the system subroutine returns a value of 127. In
all cases, the errno global variable is set to indicate the error.