这里
strcpy(a, system("echo Hello | base64"));
system() 不会将其结果存储到数组 a 中,因为 system() 工作是执行参数中提供的 command 并在控制台上打印它,即 stdout 缓冲区。来自system的手册页
system() 通过调用执行command 中指定的命令
/bin/sh -c
命令,并在命令完成后返回。
有一种方法可以解决该问题,即您可以将其输出重定向到文件然后从文件中读取,而不是在stdout 上打印system() 输出> & 打印。例如
int main(void) {
close(1); /* stdout file descriptor is avilable now */
/* create the file if doesn't exist, if exist truncate the content to 0 length */
int fd = open("data.txt",O_CREAT|O_TRUNC|O_RDWR,0664); /* fd gets assigned with lowest
available fd i.e 1 i.e nowonwards stdout output
gets rediredcted to file */
if(fd == -1) {
/* @TODO error handling */
return 0;
}
system("echo Hello | base64"); /* system output gets stored in file */
int max_char = lseek(fd,0,2);/* make fd to point to end, get the max no of char */
char *a = malloc(max_char + 1); /* to avoid buffer overflow or
underflow, allocate memory only equal to the max no of char in file */
if(a == NULL) {
/* @TODO error handling if malloc fails */
return 0;
}
lseek(fd,0,0);/* from beginning of file */
int ret = read(fd,a,max_char);/* now read out put of system() from
file as array and print it */
if(ret == -1) {
/* @TODO error handling */
return 0;
}
a[ret] = '\0';/* \0 terminated array */
dup2(0,fd);/*fd 0 duplicated to file descriptor where fd points i.e */
printf("output : %s \n", a);
/* to avoid memory leak, free the dynamic memory */
free(a);
return 0;
}
我的上述建议是一个临时修复,我不会推荐这个,而是按照@chris Turner (http://man7.org/linux/man-pages/man3/popen.3.html) 的建议使用 [popen],它说
popen() 函数通过创建管道、分叉、
和
调用外壳。由于管道根据定义是单向的,因此
type 参数只能指定 reading 或 writing,不能同时指定两者;这
结果流相应地是只读或只写的。
例如
int main(void) {
char buf[1024];
FILE *fp = popen("echo Hello | base64","r");
printf("%s\n",fgets(buf,sizeof(buf),fp));
return 0;
}