Hello,
I have the following code that is supposed a parent and two childs. It works, but it doesn't look right in terms of process creation. I am confused about the part in star comments. Thanks.
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#define CHILD 1
#define PARENT 0
#define BUF_SIZE 512
void perror_exit(const char *msg)
{
perror(msg);
exit(1);
}
void socketpair2(int *sock_fd)
{
if(socketpair(AF_LOCAL, SOCK_STREAM, 0, sock_fd) < 0)
perror_exit("socketpair");
}
/*
* creates a new process and returns return value of fork()
*/
int fork2()
{
int pid;
if((pid = fork()) < 0)
perror("fork"), exit(1);
return pid;
}
void app_layer(int sock_fd1[], int sock_fd2[])
{
char buf[BUF_SIZE];
char buf2[BUF_SIZE];
buf[0] = 0;
buf2[0] = 0;
close(sock_fd1[CHILD]);
close(sock_fd2[CHILD]);
strcpy(buf, "APP TO IP/ICMP 1 ");
if(write(sock_fd1[PARENT], buf, BUF_SIZE) < 0)
perror_exit("write app_layer");
strcpy(buf2, "APP TO IP/ICMP 2 ");
if(write(sock_fd2[PARENT], buf2, BUF_SIZE) < 0)
perror_exit("write app_layer");
if(read(sock_fd1[PARENT], buf, BUF_SIZE) < 0)
perror_exit("read");
if(read(sock_fd2[PARENT], buf2, BUF_SIZE) < 0)
perror_exit("read");
printf("%s\n%s\n", buf, buf2);
}
void ip_icmp_layer(int sock_fd[], char *str)
{
char buf[BUF_SIZE];
close(sock_fd[PARENT]);
if(read(sock_fd[CHILD], buf, BUF_SIZE) < 0)
perror_exit("read");
strcat(buf, str);
strcat(buf, " IP/ICMP TO APP");
if(write(sock_fd[CHILD], buf, BUF_SIZE) < 0)
perror_exit("write");
}
int main()
{
int pid;
int sock1[2], sock2[2];
// create a parent with two childs NOT child and grandchild
socketpair2(sock1);
socketpair2(sock2);
pid = fork2();
if(pid)
{
//*****************
pid = fork2();
if(pid)
app_layer(sock1, sock2);
else
ip_icmp_layer(sock2, "22");
//*****************
}
else
ip_icmp_layer(sock1, "11");
return 0;
}