【发布时间】:2016-02-02 09:52:33
【问题描述】:
我将像 ls 这样的命令作为输入并使用 popen 执行命令并将结果存储在缓冲区中。但是,它不会打印命令的所有内容。请帮我。 PS 当整个代码都在 main 中时它能够工作。我已经尝试过 gdb 但我无法进行调试。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
void process_command(char * command, char * buffer)
{
int fd[2], nbytes;
pid_t childpid;
char readbuffer[1025];
FILE *fp = NULL;
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
int b = 0;
int status = 0;
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
fp = popen(command,"r");
/* Send "string" through the output side of pipe */
while((b = fread(readbuffer,1,1024,fp)) > 0)
write(fd[1], readbuffer, b);
status = pclose(fp);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
waitpid(childpid,&status,0);
/* Read in a string from the pipe */
do
{
nbytes = read(fd[0], buffer, sizeof(buffer));
}while(nbytes == -1);
buffer[nbytes] = '\0';
printf("Received string: %s", buffer);
}
}
#define MAX 1024
int main(void)
{
char command[MAX] ;
char buffer[MAX];
scanf("%s",command);
process_command(command,buffer);
return(0);
}
【问题讨论】:
-
为什么是孩子和父母?为什么不直接写信给
buffer? -
缓冲区写入不完整的问题。