在C語言中執行shell命令

來源:互聯網
上載者:User

在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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.