Thread: Communication through pipes

  1. #1
    C Beginner
    Join Date
    Dec 2011
    Location
    Portugal
    Posts
    187

    Communication through pipes

    Hello everyone,
    I'm trying to communicate between father and son processes using pipes.

    Wouldn't this be the proper way for the son to communicate with his father ?

    Code:
    
     else if(pid==0) {
            /* son */
            dup2(fd[1],1);
            close(fd[1]);
            write(fd[1],buffer,1000);
            int a = execlp(cmd,cmd,arg,NULL);
            _exit(pid); // son dies
     }
     
     wait(&pid); 
     read(fd[0],buffer,strlen(arg));

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > write(fd[1],buffer,1000);
    You just closed this descriptor.
    Try writing to descriptor 1.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    C Beginner
    Join Date
    Dec 2011
    Location
    Portugal
    Posts
    187
    Tried that.
    After
    Code:
    read(fd[0],buffer,strlen(arg));
    I have this printf :
    Code:
    printf("-----> %s \n",buffer);
    And it prints all NULL.

    Why ain't it reading properly ? :/

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    Perhaps you could post a small and complete program which demonstrates the problem.
    There's too much missing in your post to make any kind of guess as to what you messed up.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    C Beginner
    Join Date
    Dec 2011
    Location
    Portugal
    Posts
    187
    Here it is Salem :

    Code:
        void map(char* cmd, char *arg){    int i;
        int pid;
        int fd[2];
        char* buffer;
        char* novo;
        int status;
        FILE *stream;
        pipe(fd);
        pid=fork();
        stream = fopen("merdas.txt","a+");
    
    
        if(pid==-1) /* erro */
        {
            perror("impossivel de criar um filho") ;
            exit(-1) ;
        }
        else if(pid==0) {
            /* filho */
            dup2(fd[1],1);
            close(fd[1]);
           // read(1,buffer,1000);
            printf("li %s\n",&buffer);
            //write(1,buffer,1000);
            printf("buffer:a%sa\n",&buffer);
            printf("Resultado do execlp:\n");
            int a = execlp(cmd,cmd,arg,NULL); //o comando é o primeiro argumento da main e o argumento é a linha/ficheiro...
            
            _exit(pid); //filho morra
            //sleep(1);
        }
        printf("adoro merda antes do wait \n");
        wait(&pid); //esperar que o filho termine
        printf("ainda mais depois \n");
        /*dup2(fd[0],fd[1]);
        close(fd[0]);*/
        //fprintf(stream,"%s\n",buffer);
        read(0,buffer,strlen(arg));
        printf("-----> %s \n",buffer);
    }
    
    
    int main(int argc, char** argv){
       // FILE *stream;
        char *str;
        //if((stream = freopen("merdas.txt", "w", stdout)) == NULL)
            //exit(-1);
        //stream = fopen("merdas.txt","a+");
        char *aux;
        size_t tam=0;
        int line=0;
        int i;
        //  init();
       // printf("iq\n");
        while(line=getline(&str,&tam,stdin)!=-1){
            tam=strlen(str);
            str[tam-1]='\0';
            map(argv[1],str);
          //  fprintf(stream,"%s\n",str);
        }
        //fprintf(stream,"END");
        //freopen ("/dev/tty", "a", stdout);
        //map2();
        return(1);
     
    }

  6. #6
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Read the manual page for dup2. What does this function do? What is its return value? Are you using this function properly?

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > char* buffer;
    Where does this point?

    > printf("li %s\n",&buffer);
    You use buffer and &buffer like they were interchangeable.
    Whist this is true (value wise at least, the types are always different) for a true array, you can't to the same thing with pointers.

    > stream = fopen("merdas.txt","a+");
    Do this before the fork, not after.

    Doing this after means one process will fail, because two processes can't write to the same file.


    > _exit(pid); //filho morra
    exit takes a small integer result, not a process ID.
    Typically, _exit(EXIT_FAILURE) when it's all gone wrong.

    > while(line=getline(&str,&tam,stdin)!=-1)
    You should initialise str to NULL before calling this for the first time, otherwise it will just try to do something stupid with the garbage pointer.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    C Beginner
    Join Date
    Dec 2011
    Location
    Portugal
    Posts
    187
    Quote Originally Posted by Salem View Post
    > char* buffer;
    Where does this point?

    Having char* buffer and char buffer[] is the same thing I guess.


    > printf("li %s\n",&buffer);
    You use buffer and &buffer like they were interchangeable.
    Whist this is true (value wise at least, the types are always different) for a true array, you can't to the same thing with pointers.

    > stream = fopen("merdas.txt","a+");
    Do this before the fork, not after.

    Doing this after means one process will fail, because two processes can't write to the same file.

    I've done this, thanks.

    > _exit(pid); //filho morra
    exit takes a small integer result, not a process ID.
    Typically, _exit(EXIT_FAILURE) when it's all gone wrong.

    Done, thanks.


    > while(line=getline(&str,&tam,stdin)!=-1)
    You should initialise str to NULL before calling this for the first time, otherwise it will just try to do something stupid with the garbage pointer.
    Done aswell, thanks for the tip.

  9. #9
    C Beginner
    Join Date
    Dec 2011
    Location
    Portugal
    Posts
    187
    I've changed my whole function.
    It looks like this now :

    Code:
    void map(char* cmd, char* arg){
        int i;
        int d=0;
        int pid;
        FILE *stream ;
        int *status;
        
        char* buffer;
        stream = fopen("merdas.txt","a");
        int fd[2];
        if(pipe(fd)==-1){perror("demo");exit(1);}
        if ((pid = fork()) == -1)   {perror("demo"); exit(1);}
        else
            waitpid(-1, &status, 0);
        
        if(pid==0) // filho
        {
            dup2(fd[1],1);
            printf("filho\n");
            // printf("o arg é %s",arg);
            int a = execlp(cmd,cmd,arg,NULL); //o comando é o primeiro argumento da main e o argumento é a linha/ficheiro...
            //  printf("ja acabou - %d\n",a);
            perror("demo");
            //_exit(pid); //filho morra
        }
        else{
            printf("pai\n");
            while((d=read(1,buffer,1000))>0) {
                printf("ola");
                buffer[d] = '\0';
                printf("<<<<%s\n",buffer);
            }
            
            exit(0);
        }
    }
    Still doesn't work, it keeps on standby!
    Last edited by DeanWinchester; 06-01-2013 at 10:05 AM.

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > Having char* buffer and char buffer[] is the same thing I guess.
    Guess again.

    Try with
    char buffer[1001];

    > stream = fopen("merdas.txt","a");
    I know I said before the fork, but having looked at it again, it might be better if you only did this in the parent.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #11
    C Beginner
    Join Date
    Dec 2011
    Location
    Portugal
    Posts
    187
    Quote Originally Posted by Salem View Post
    > Having char* buffer and char buffer[] is the same thing I guess.
    Guess again.

    Try with
    char buffer[1001];

    > stream = fopen("merdas.txt","a");
    I know I said before the fork, but having looked at it again, it might be better if you only did this in the parent.
    Thanks for the kind replies and explanation.
    I found out what's happening, I just do not know how to solve it.

    Thing is my wait function isn't working, this :
    Code:
    else
            waitpid(-1, &status, 0);     

    For some reason waitpid isn't working and my function is going straight to the parent process, not going to the son and therefor not doing exec .

    Any idea on why this is happening ? :/

  12. #12
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > int *status;
    ...
    > waitpid(-1, &status, 0);
    Please tell me you're getting compiler warnings for this.

    Fix ALL warnings before trying to run the code.

    I would go so far as to suggest you add -Werror to the compiler command line to stop you from running code with warnings still present.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  13. #13
    C Beginner
    Join Date
    Dec 2011
    Location
    Portugal
    Posts
    187
    Quote Originally Posted by Salem View Post
    > int *status;
    ...
    > waitpid(-1, &status, 0);
    Please tell me you're getting compiler warnings for this.

    Fix ALL warnings before trying to run the code.

    I would go so far as to suggest you add -Werror to the compiler command line to stop you from running code with warnings still present.

    cc1: warnings being treated as errors
    soluis2.c: In function ‘map2’:
    soluis2.c:93: warning: format ‘%s’ expects type ‘char *’, but argument 4 has type ‘char (*)[1000]’
    soluis2.c:93: warning: format ‘%s’ expects type ‘char *’, but argument 4 has type ‘char (*)[1000]’
    soluis2.c: In function ‘map’:
    soluis2.c:143: warning: passing argument 2 of ‘waitpid’ from incompatible pointer type

    Thanks, I'll fix these warnings and see what I get.

  14. #14
    C Beginner
    Join Date
    Dec 2011
    Location
    Portugal
    Posts
    187
    Doing instead
    Code:
    waitpid(-1, status, 0);
    Managed to cut the error out but still it won't work >_>

  15. #15
    Registered User
    Join Date
    Mar 2010
    Posts
    583
    Code:
        if(pipe(fd)==-1){perror("demo");exit(1);}
        if ((pid = fork()) == -1)   {perror("demo"); exit(1);}
        else
            waitpid(-1, &status, 0);
        
        if(pid==0) // filho
        {
            dup2(fd[1],1);
    That doesn't look right. Assuming the fork() succeeds, then the child will have pid 0 and the parent will have its pid. So having done the fork, both the parent and the child will go to waitpid() because neither pid is -1.

    You need to sort out your types and make sure you're not passing garbage pointers all over the place.
    Code:
     int *status; // this is an uninitialised int pointer. 
     char* buffer; // again uninitialised pointer, trying to write to this could crash your program or cause weird behaviour
     char buffer[1000]; // this has statically allocated 1000 bytes of space. So you can actually write to this
     int status2;  // Just an int. You can use &status to pass the address where an int* is required, and just read it as a normal int here.
    If you pass status to waitpid correctly you can check it and find out why it didn't stop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help using pipes
    By demonofnight in forum C++ Programming
    Replies: 5
    Last Post: 12-27-2011, 08:48 AM
  2. Pipes
    By Sharan in forum C Programming
    Replies: 1
    Last Post: 02-08-2006, 06:51 AM
  3. pipes in c
    By ajal1 in forum C Programming
    Replies: 6
    Last Post: 10-29-2005, 03:29 PM
  4. pipes
    By moi in forum C Programming
    Replies: 8
    Last Post: 08-11-2004, 01:59 PM
  5. Need some help with pipes please.
    By carrja99 in forum C Programming
    Replies: 1
    Last Post: 05-05-2004, 04:13 PM