creating multi process application in linux is a complex task. It requires good knowledge of linux system call. multi process application needs to communicate each other. one of measure problem every developer faces, is “race condition”. multi process application design must avoid race condition or deadlock condition. Let us discuss some available system calls which are used to create multiprocess application.

The fork() System Call

  • If fork() returns a negative value, when it fails to create child process.
  • fork() returns a zero to a newly created child process.
  • fork() returns a positive value (process ID of the child process) , to the parent process

Socketpair() system call C/Unix/Linux

 int socketpair(int domain, int type, int protocol, int sv[2]);

 The socketpair() call creates an unnamed pair of connected sockets in
       the specified domain, of the specified type, and using the optionally
       specified protocol.  For further details of these arguments, see
       socket(2).

       The file descriptors used in referencing the new sockets are returned
       in sv[0] and sv[1].  The two sockets are indistinguishable.

calling socketpair system call creates a pair of connected sockets. Through Socket pairs we can achieve a two-way communication chanel.  Messages can be sent in both directions. we can allocate one end to be the parent and one to be the child end. It doesn’t matter which end, just make a choice and remember the allocation.

sample example of creating multi process application in linux

#include<iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include<unistd.h>
#include<cstdio>
#include <cstdlib>
using namespace std;

void child_msg(int socket) {
	const char hello[] = "hello parent, I am child";
	write(socket, hello, sizeof(hello));
}

void parent_proc(int socket) {
	char buf[1024];
	int n = read(socket, buf, sizeof(buf));
	printf("parent received '%.*s'\n", n, buf);
}

int main() {
	pid_t child;
	int sockets[2];

	if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) {
		perror("error opening socket pair");
		exit(1);
	}
	child = fork();
	if (child) //parent process
	{
		close(sockets[0]);
		parent_proc(sockets[1]);
		close(sockets[1]);
	} else // child process
	{
		close(sockets[1]);
		child_msg(sockets[0]);
		close(sockets[0]);
	}
	return 0;
}

How it works

  • Before creating a new process through fork, we made socket pair.
  • After fork we detect parent process and child proces.
  • In the parent process we have closed one end of socket pairs and calls parent_proc(sockets[1]).
  • In the child process we have closed other end of socket pairs and calls child_msg(sockets[0]).

Ref:

http://man7.org/linux/man-pages/man2/socketpair.2.html




Related Contents to follow