#include#define BUFSIZE PIPE_BUF
void err_quit(char *msg)
{
printf(msg);
exit(1);
}
int main(void)
{
int fd[2];
char buf[BUFSIZE] = "hello my brother!\n";
pid_t pid;
int len;
// create pipe
if((pipe(fd))<0)
err_quit("pipe failed\n");
// create the son process1
pid = fork();
if(pid < 0)
err_quit("fork failed\n");
else if(pid == 0)// son process1
{
close(fd[0]);// close read port
write(fd[1], buf, strlen(buf));// write
printf("I am son process1(ID:%d), write pipe ok\n", getpid());
exit(0);
}
// create the son process2
pid = fork();
if(pid < 0)
err_quit("fork failed\n");
else if(pid > 0)
{
close(fd[0]);// close read port
close(fd[1]);// close write port
printf("I am parent process(ID:%d), close my pipe\n", getpid());
exit(0);
}
else
{
close(fd[1]);// close write port
len = read(fd[0], buf, BUFSIZE);// read
printf("I am son process2(ID:%d), read pipe ok\n", getpid());
write(STDOUT_FILENO, buf, len);
exit(0);
}
return 0;
}
编译后执行:
$ ./brother_pipe
I am parent process(ID:4962), close my pipe
I am son process1(ID:4963), write pipe ok
I am son process2(ID:4964), read pipe ok
hello my brother!
上述程序中父进程分别建立了两个子进程,子进程1中关闭了管道的读出端,子进程2中关闭了管道的输入端,并父进程中关闭了管道的两端,从而构成了从子进程1到子进程2的管道。另外,程序中父进程创建第1个子进程时并没有关闭管道两端,而是创建第2个子进程时才关闭管道,这是为了创建第2个进程时,子进程可以继承存活的管道。
参考:《精通Linux C编程》- 程国钢
附:fork()函数的使用示例,参考:https://blog.csdn.net/jason314/article/details/5640969
#include #include int main ()
{
pid_t fpid; //fpid表示fork函数返回的值
int count=0;
fpid=fork();
if (fpid < 0)
printf("error in fork!");
// son process see fpid as 0
else if (fpid == 0)
{
printf("I am the child process, my process id:%d\n",getpid());
count++;
}
// parent process see fpid as a non 0 num
else// (fpid > 0)
{
printf("I am the parent process, my process id: %d\n",getpid());
count++;
}
printf("统计结果是: %d\n",count);
return 0;
}
运行结果:
./forktest
I am the parent process, my process id: 5892
统计结果是: 1
I am the child process, my process id:5893
统计结果是: 1