天天看點

在C語言中執行shell指令

在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>

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"

char *argv[] = {"ls", "-al", "/etc/passwd", "char*"};

if(vfork() == 0)

execv("/bin/ls", argv);

else

printf("parent.\n")

原文

[1]http://www.cnblogs.com/niocai/archive/2011/07/20/2111896.html

上一篇: dmesg簡介

繼續閱讀