shell c 混合编程 system 输出数据到变量
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;
}
完