shell c 混合編程 system 輸出資料到變數

來源:互聯網
上載者:User

shell c 混合編程 system 輸出資料到變數

方法一: (popen)

#include <stdio.h>
#include <stdlib.h>


int main( int argc, char *argv[] )
{

FILE *fp;
int status;
char path[1035];

/* Open the command for reading. */
fp = popen("/bin/ls /etc/", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit;
}

/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
}

/* close */
pclose(fp);

return 0;
}

方法二:

#include <stdio.h>
#include <stdlib.h>



static int my_system(const char* pCmd, char* pResult, int size)
{
int fd[2];
int pid;
int count;
int left;
char* p = 0;
int maxlen = size - 1;
memset(pResult, 0, size);
if(pipe(fd))
{
printf("pipe error\n");
return -1;
}
if((pid = fork()) == 0)
{// chile process
int fd2[2];
if(pipe(fd2))
{
printf("pipe2 error\n");
return -1;
}
close(1);
dup2(fd2[1],1);
close(fd[0]);
close(fd2[1]);
system(pCmd);
read(fd2[0], pResult, maxlen);
pResult[strlen(pResult)-1] = 0;
write(fd[1], pResult, strlen(pResult));
close(fd2[0]);
exit(0);
}
// parent process
close(fd[1]);
p = pResult;
left = maxlen;
while((count = read(fd[0], p, left))) {
p = count;
left -= count;
if(left == 0)
break;
}
close(fd[0]);
return 0;
}
int main(void)
{
char result[1025];
my_system("LC_ALL=C ifconfig", result, 1025);
printf("the result is\n\n%s\n", result);
return 0;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.