在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