0

別のプログラムの出力をソケットにリダイレクトしようとしています。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);  

 }  
}`
4

1 に答える 1

0

Umm, this is kinda a mess -- right off the top of my head:

  1. To be safe this my_addr should have been zeroed before this: my_addr.sin_family = AF_INET
  2. Check the returns of syscalls!!
  3. Not a good idea to cast malloc's return: mex=(char*)malloc(sizeof(int)+1);
  4. I hope this length includes the '\0' byte: read (fd2,&lenght,sizeof(int));
  5. If stringa isn't nul-terminated, this is trouble: lstat(stringa, &buf)
  6. You realize that this ends your program, right: execl("/bin/ls","ls",(char*)0);?

I'm sure there are more...

于 2016-01-08T21:37:48.870 に答える