cifz
cifz

Reputation: 1078

Using pipe for IPC

I'm currently studying IPC, I have a first program

A: Do an exec for B and wait

B: Receive through a fifo a string from a third program "C" and have to resend it to A

I was thinking to open a pipe in A before the exec, then passing fd[1] to B as an argument

if(pipe(fd)==-1){
    perror("Pipe Failed");
    myExit(EXIT_FAILURE);
}

close(fd[1]);   
sprintf(fdString,"%d",fd[1]);

    .......

if((int)(pid=fork())>0)

    waiting(status);    

else if(pid==0){    

    close(fd[0]);   

    execl("./B","B",fdString,(char*)0);
    perror("Exec failed");
    myExit(EXIT_FAILURE);

}

Then in B:

int fd=atoi(argv[1]);

    //Receive string from C 

    len=strlen(string)+1;

if(write(fd,&len,sizeof(int))==-1){
    perror("Error on writing length");
    exit(EXIT_FAILURE); 
}

if(write(fd,string,len)==-1){
    perror("Error on writing string");
    exit(EXIT_FAILURE);     
}

My problem now is reading this string in A. I was thinking something to send a SIGUSR1 to A as soon as the string is written by B on the pipe and having in A something like:

signal(SIGUSR1, signalHandler);
    ........
    static void signalHandler(int signo){
    switch(signo){
    case SIGUSR1:
        listen();
        break;
    default: break;

    }
}
    ........
static void listen(){

    int len;

    if(read(fd[0],&len,sizeof(int))<sizeof(int)){
        perror("Error reading len");
        myExit(EXIT_FAILURE);   
    }

    char string[len];

    if(read(fd[0],&string,len)<len){
        perror("Error reading string");
        myExit(EXIT_FAILURE);   
    }
    printf("String: %s with length %d\n", string, len);
}

However what I get is "Error reading len: Success" , what's wrong ?

Sorry if my English is bad, any help is appreciated, thanks!

Upvotes: 1

Views: 435

Answers (2)

cifz
cifz

Reputation: 1078

I'm answering by myself because I've actually solved my own problem:

I closed fd[1] before of fork(), that will cause the child having fd[1] closed (bringing to error on the read!) as Ethanol (C2H5OH ;)) said.

I'm accepting his answer 'cause it brought me towards the solution!

Upvotes: 0

C2H5OH
C2H5OH

Reputation: 5602

The program that writes the string is very likely to be segfaulting because of this line:

if(write(fd,&string,len)==-1) { /* ... */

As you should pass string whithout the &.

On the other hand, your error message is not very informative because read() is probably returning 0 or less than sizeof(int) bytes. It will only set errno when the return value is -1. The fact that read() returns 0 or less than expected usually means an end of file condition, i.e. the other end has closed the pipe.

You should fix these issues before trying to dig any further.

Upvotes: 1

Related Questions