linux创建一个匿名管道,Linux匿名管道及实例

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值