我正在尝试将另一个程序的输出重定向到套接字, 我尝试过dup2(STDOUT_FILE,socketfd);服务器源代码中的execl(“/ bin / ls”,“ls”,(char *)0)和客户端源代码中的read(socketfd,buff,1)..但客户端的输出似乎只是一个空字符串..
int main(){
struct sockaddr_in my_addr;
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(5200);
my_addr.sin_addr.s_addr= htonl (INADDR_ANY);
int fd1, fd2;
fd1=socket (PF_INET, SOCK_STREAM, 0);
bind (fd1, (struct sockaddr *) &my_addr, sizeof(my_addr));
listen (fd1, 5);
while (1){
fd2= accept (fd1, NULL,NULL);
char *stringa,*mex;
int lenght;
struct stat buf;
mex=(char*)malloc(sizeof(int)+1);
read (fd2,&lenght,sizeof(int));
stringa=(char*)malloc(sizeof(char)*lenght);
read(fd2,stringa,lenght);
write (1,"\n",1);
if (lstat(stringa, &buf)<0){
sprintf(mex,"%d",-1);
write (fd2,mex,sizeof(int));
}
else if (S_ISDIR(buf.st_mode)){
DIR* direct= opendir(stringa);
struct dirent *directory;
int howmany=0;
while((directory=readdir(direct))!=NULL){
lstat(directory->d_name,&buf);
if (S_ISREG(buf.st_mode))
howmany++;
}
sprintf(mex,"%d",howmany);
write (fd2,mex,sizeof(int));
}else if (buf.st_mode & S_IXUSR){
dup2(STDOUT_FILENO, fd2);
execl("/bin/ls","ls",(char*)0);
}
write (fd2,"$",1);
}
}`
答案 0 :(得分:0)
my_addr
应该在此之前归零:
my_addr.sin_family = AF_INET
mex=(char*)malloc(sizeof(int)+1);
read (fd2,&lenght,sizeof(int));
stringa
未终止,则会遇到麻烦:lstat(stringa, &buf)
execl("/bin/ls","ls",(char*)0);
?我确信还有更多...