Search code examples
csocketsunixprocess

How to create a socket between 2 processes after fork-exec


i'm learning C and this is my problem: i need to connect 2 processes with a socket AF_UNIX. My question is: how can i achieve that ?

I've already tried something with poor results:

  • Tried to pass the fd.

  • Tried to dup but again failed and the 2 processes didn't take any messages from the parent process.

Can i just open a socket in parent and then pass the file descriptor with execl ? or should i just try something more "complicated" ?

EDIT: code this is P1.c

int main (){

  printf("Hello this is process 1\n");
int fd=open("./foo",O_RDWR);
int h=fork();
if(h==0)
{
    sleep(2);
    dup2(fd,0);//note we will be loosing standard input in p2
    execvp("./client",NULL);
}
else
{
    printf("This is from p1 process\n");
    write(fd,"buf",4);
                //do some process with p1
    printf("This is end of p1 process\n");
}

return 0;

}

this is P2.c

int main (int argc, char * argv[]){
int fd=atoi(argv[1]);      
char buf[1024];
int n=read(fd,buf,1024);
buf[n]='\0';
printf("This is from p2\n");
write(1,buf,strlen(buf));
    exit(EXIT_SUCCESS);

}

note: i wasn't trying to use a socket.


Solution

  • Here is a description of unix sockets and an example in code.

    The above link seems dead, but the Wayback Machine remembers

    You need to designate one of the forked processes as server, and the other as client. In the server, you have to wait for connections. In the client, you have to establish the communication.

    In the link are examples of each service. Don't be alarmed by the length of the code - most of it is comment.

    Note that if you just want 'local' communication between processes, you might want to look into IPC: fifos, shared memory, message passing. They are much easier to implement.