Skip to content

Instantly share code, notes, and snippets.

@defp
Created May 27, 2012 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save defp/2802508 to your computer and use it in GitHub Desktop.
Save defp/2802508 to your computer and use it in GitHub Desktop.
linux pipe
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_DATA_LEN 256
#define DELAY_TIME 1
int main(){
pid_t pid;
int pipe_fd[2];
char buf[MAX_DATA_LEN];
const char data[] = "pipe test";
int real_read, real_write;
memset((void *)buf, 0, sizeof(buf));
/* 创建管道*/
if(pipe(pipe_fd) < 0){
printf("pipe create error\n");
exit(1);
}
if((pid = fork()) == 0 ) {
close(pipe_fd[1]);
/*子进程关闭写描述符*/
sleep(DELAY_TIME * 3);
if ((real_read = read(pipe_fd[0], buf, MAX_DATA_LEN)) >0) {
printf("%d bytes read from the pipe is '%s'\n", real_read, buf);
}
close(pipe_fd[0]);
exit(0);
}
else if (pid >0) {
/* 关闭父进程读描述符 */
close(pipe_fd[0]);
sleep(DELAY_TIME);
if ((real_write = write(pipe_fd[1], data, strlen(data))) != -1) {
printf("parent wrote %d bytes:'%s'\n", real_write, data);
}
close(pipe_fd[1]);
waitpid(pid, NULL, 0);
exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment