Linux 进程间通信(IPC)


Linux 进程间通信(IPC):

  Linux系统中除了进程和进程之间通信,我想大家也应该关注用户空间与内核空间是怎样通信的。例如说netlink等等。

除了传统进程间通信外像Socket通信也须要掌握的!

/*--------------------------------------------------------------------------
 * Project: aipc.c
 * Name: zwp
 * Date: 2014/6
 *-------------------------------------------------------------------------*/


#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>


#define MAXLINE	1024

static void sig_pipe(int);

int s_pipe(int fd[2]);


int main(void)
{
	int	n, fd[2];
	pid_t	pid;
	char	line[MAXLINE];
	
	if(signal(SIGPIPE, sig_pipe) == SIG_ERR)
		printf("signal error...\n");
	if(s_pipe(fd) < 0)
		printf("pipe error...\n");
	else if(pid > 0)
	{
		close(fd[1]);
		while(fgets(line, MAXLINE, stdin) != NULL)
		{ 
			n = strlen(line);

			if(write(fd[0], line, MAXLINE) != n)
				printf("write error from pipe...\n");
			if((n = read(fd[0], line, MAXLINE)) < 0)
				printf("read arror from pipe...\n");
			if(n == 0)
			{
				printf("child closed pipe...\n");
				break;
			}
			line[n] = 0;
			if(fputs(line, stdout) == EOF)
				printf("fputs error...\n");
		}
		if(ferror(stdin))
			printf("fgets error on stdin...\n");

		exit(0);

		
	}
	else
	{
		close(fd[0]);
		if(fd[1] != STDIN_FILENO)
		{
			if(dup2(fd[1], STDIN_FILENO) != STDIN_FILENO)
				printf("dup2 error to stdin...\n");
			
		}
		if(fd[1] != STDOUT_FILENO)
		{
			if(dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
				printf("dup2 error tostdout..\n");

		}
		if(execl("./add2", "add2", NULL) < 0)
			printf("execl error...\n");


	}
		
}

int s_pipe(int fd[2])
{
	return (socketpair(AF_UNIX, SOCK_STREAM, 0, fd));

}

static void sig_pipe(int sign)
{
	printf("SIGPIPE caught...\n");
	exit(1);

}


 

posted @ 2017-06-13 15:48  zhchoutai  阅读(210)  评论(0编辑  收藏  举报