码迷,mamicode.com
首页 > 系统相关 > 详细

Linux 进程间通信(IPC)

时间:2014-06-17 23:08:03      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:linux


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);

}


 

Linux 进程间通信(IPC),布布扣,bubuko.com

Linux 进程间通信(IPC)

标签:linux

原文地址:http://blog.csdn.net/qqzwp/article/details/31403133

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!