歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> C、Shell混合編程小技巧

C、Shell混合編程小技巧

日期:2017/3/1 9:33:20   编辑:SHELL編程

寫在前面:

開始工作的前兩年一直都是在Windows平台下,使用的編程方式多是單一語言,全部使用C++,或全部使用C#,或者java等等等。

在最近換了工作,投奔互聯網之後,開發平台徹底轉移到Linux平台,告別了Win7,用上了mac,哈哈。

言歸正傳:

int system(const char *);

Linux c 中的system函數的作用是在程序中調用shell。我的小技巧的思路就是將system函數的執行結果讀取回來。返回的結果是字符串,不要小瞧這個字符串,經過巧妙的設計,該技巧可以幫助我做很多很奇妙的事情。

例如:我在程序中的關於配置信息讀取的部分就都是寫在python文件中,當我需要讀取配置的時候,我會去執行python腳本來得到我需要的結果。這麼做的好處之一就是寫在python文件中的數據結構可以自己隨意按需求定義,而不是拘泥於傳統的ini、json、xml的定義方式。

代碼:

int main(int argc, char **argv)
{
char result[1025];
my_system("ls -al", result, 1025);
printf("the result is\n\n%s\n", result);

return 0;
}

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 errorn");
return -1;
}
if((pid = fork()) == 0)
{// chile process
int fd2[2];
if(pipe(fd2)){
printf("pipe2 errorn");
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;
}

Copyright © Linux教程網 All Rights Reserved