在C語言中執行shell命令
1、system系統調用
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()會繼承環境變數,通過環境變數可能會造成系統安全的問題。Use the exec(3) family of functions instead, but not execlp(3) or execvp(3).
#include<stdlib.h>
int main()
{
system("ls -al /data/myname");
return 1;
}
2)popen(建立管道I/O)
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
popen()會調用fork()產生子進程,然後從子進程中調用/bin/sh -c command來執行參數command的指令。依照此type(r,w)值,popen()會建立管道連到子進程的標準輸出裝置或標準輸入裝置,然後返回一個檔案指標。隨後進程便可利用此檔案指標來讀取子進程的輸出裝置或是寫入到子進程的標準輸入裝置中。此外,所有使用檔案指標(FILE*)操作的函數也都可以使用,除了fclose()以外。
Since a pipe is by definition unidirectional, the type argument may specify only reading or writing, not both; the resulting stream is correspondingly read-only or write-only.
傳回值,若成功則返迴文件指標,否則返回NULL,錯誤原因存於errno中。
在編寫具SUID/SGID許可權的程式時請盡量避免使用popen(),popen()會繼承環境變數,通過環境變數可能會造成系統安全的問題。
#include<stdio.h>
int main()
{
FILE *fp;
char buffer[80];
fp=popen("cat /etc/passwd","r");
fgets(buffer,sizeof(buffer),fp);
printf("%s",buffer);
pclose(fp);
return 0;
}
3)使用vfork()建立子進程,然後調用exec函數族
#include "unistd.h"
#include "stdio.h"
int main()
{
char *argv[] = {"ls", "-al", "/etc/passwd", "char*"};
if(vfork() == 0)
{
execv("/bin/ls", argv);
}
else
{
printf("parent.\n")
}
return 0;
}
原文
[1]http://www.cnblogs.com/niocai/archive/2011/07/20/2111896.html