0

I'm trying to redirect to a socket the output of another program, I've tried with dup2 (STDOUT_FILE, socketfd); execl("/bin/ls","ls",(char*)0) in the Server's source code, and the read (socketfd,buff,1) in the Client source code.. But the output of the Client seems just an empty string..

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);  

 }  
}`
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Luigi Blu
  • 129
  • 13

1 Answers1

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...

John Hascall
  • 9,176
  • 6
  • 48
  • 72
  • it doesn't matter, I'm just trying to practice the redirect of stdout of the exec function.. So, how can i do? I don't think that to cast malloc's return is meaning something for my problem.. – Luigi Blu Jan 09 '16 at 11:24