Skip to content

Instantly share code, notes, and snippets.

@VOID001 VOID001/ipc_pipe.c
Created May 10, 2016

Embed
What would you like to do?
/*************************************************************************
> File Name: ipc_pipe.c
> Author: VOID_133
> IPC(InterProcess Communication) Use Pipe
> Mail: ###################
> Created Time: Tue 10 May 2016 06:51:27 PM CST
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/file.h>
#include<sys/wait.h>
char buf_1[] = "Hi, parent, I am your child";
char buf_2[] = "Hi, child, I am your parent";
char recvbuf[1000];
int main()
{
int pipe_fd[2];
if(pipe(pipe_fd) < 0)
perror("Create pipe error");
printf("Create pipe from [read]%d [write]%d\n", pipe_fd[0], pipe_fd[1]);
pid_t fpid = getpid();
pid_t id = fork();
if(id < 0)
perror("create child fail");
if(id == 0)
{
/* First Child Send Data to Father */
//close(pipe_fd[0]);
sleep(1);
if(write(pipe_fd[1], buf_1, strlen(buf_1) * sizeof(char)) < 0)
perror("child write error");
sleep(1);
memset(recvbuf, 0, sizeof(recvbuf));
if(read(pipe_fd[0], recvbuf, strlen(buf_2) * sizeof(char) < 0))
perror("child read error");
else
printf("Recv From Parent[%d]: %s\n", fpid, recvbuf);
}
else
{
/* First Child Send Data to Father */
//close(pipe_fd[1]);
sleep(1);
memset(recvbuf, 0, sizeof(recvbuf));
if(read(pipe_fd[0], recvbuf, strlen(buf_1) * sizeof(char)) < 0)
perror("parent read error");
printf("Recv from Child[%d]: %s\n", id, recvbuf);
//sleep(1);
fflush(NULL);
if(write(pipe_fd[1], buf_2, strlen(buf_2) * sizeof(char)) < 0)
perror("parent write error");
else
printf("Parent Write OK\n");
sleep(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.