我正在使用子进程来执行 sha1sum 程序。对于某些上下文,基本上 sha1sum 会获取一个文件并为其创建一个唯一的代码。 (并没有完全做到这一点,但这并不重要)。 代码长度为 40 个字符。
因此,我的子进程将执行它,父进程将保存代码并将其放入缓冲区中。 我构建了一个主要函数来测试它是否正在执行我想要的操作,并且我注意到字符串不完整。我认为这是一个 malloc 问题。我对代码发表了评论,为什么我这么认为。
char* getN(char *name){
int fd[2],pid;
char *buffer = (char*)malloc(41*sizeof(char));
pipe(fd);
pid=fork();
if(!pid){
close(fd[0]);
dup2(fd[1],1);
close(fd[1]);
execlp("sha1sum","sha1sum",name,NULL);
}
else{
close(fd[1]);
read(fd[0],buffer,sizeof(buffer)); /* if i change this sizeof to like sizeof(buffer)+2 it prints 2 more chars than it previously did. no clue why. */
close(fd[0]);
wait(NULL);
}
return buffer;
}
int main(){
char *a=getN("file.pdf"); // file that's in my current directory.
printf("%s\n",a);
return 0;
}
谢谢。
最佳答案
buffer 是一个指针,而不是静态数组,因此 sizeof(buffer) 返回指针的大小。 (32 位架构上 4 个,64 位架构上 8 个)。当您调用 read 时,您不需要指针的大小,而是需要它所指向的数据的大小,因此您需要传递与作为参数传递给 malloc 的相同值(在本例中, 41)。
关于c - 尝试从管道读取字符串,但它没有读取整个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37174154/