Posted on 2010-11-01 17:46
Prayer 閱讀(5547)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
C/C++ 、
LINUX/UNIX/AIX
system(執(zhí)行shell 命令)
相關(guān)函數(shù) fork,execve,waitpid,popen
表頭文件 #include<stdlib.h>
定義函數(shù) int system(const char * string);
函數(shù)說(shuō)明 system()會(huì)調(diào)用fork()產(chǎn)生子進(jìn)程,由子進(jìn)程來(lái)調(diào)用/bin/sh-c string來(lái)執(zhí)行參數(shù)string字符串所代表的命令,此命令執(zhí)行完后隨即返回原調(diào)用的進(jìn)程。在調(diào)用system()期間SIGCHLD 信號(hào)會(huì)被暫時(shí)擱置,SIGINT和SIGQUIT 信號(hào)則會(huì)被忽略。
返回值 如果system()在調(diào)用/bin/sh時(shí)失敗則返回127,其他失敗原因返回-1。若參數(shù)string為空指針(NULL),則返回非零值。如果system()調(diào)用成功則最后會(huì)返回執(zhí)行shell命令后的返回值,但是此返回值也有可能為system()調(diào)用/bin/sh失敗所返回的127,因此最好能再檢查errno 來(lái)確認(rèn)執(zhí)行成功。
附加說(shuō)明 在編寫具有SUID/SGID權(quán)限的程序時(shí)請(qǐng)勿使用system(),system()會(huì)繼承環(huán)境變量,通過(guò)環(huán)境變量可能會(huì)造成系統(tǒng)安全的問題。
范例 #include<stdlib.h>
main()
{
system(“ls -al /etc/passwd /etc/shadow”);
}
執(zhí)行 -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.