Linux管道实验题

小编:优质农业网   人气:0℃   发布时间:2025-02-18 21:36:29
字号:

<pre t="code" l="cpp">#include <unistd.h>

Linux管道实验题

#include <stdio.h>

//警告: 该程序未做错误验证, 未关闭管道(由系统自动关闭)

int main()

{

int p2c[2]; // 该管道父进程写,子进程读

int c2p[2]; // 该管道子进程写,父进程读

// 创建2条管道

pipe(p2c);

pipe(c2p);

int pid = fork();

int fd_read, fd_write; // 这两个描述符用于保存某进程读端和写端

int pid_my; // 保存某进程自身的pid

int pid_other; // 另一进程的pid,通过

if ( pid == 0 ) { // 子进程

fd_read = p2c[0];

fd_write= c2p[1];

// 通过getpid取得自身pid,写到管道里

pid_my = getpid();

write(fd_write, pid_my, sizeof(int));

// 从另一管道读取另一进程的pid

read(fd_read, pid_other, sizeof(int));

// 打印读取到的pid

printf("Recive pid : %dn", pid_other);

} else {// p

fd_read = c2p[0];

fd_write= p2c[1];

pid_my = getpid();

// 由于子进程是先写自身pid,父进程最好先读取子进程的pid

read(fd_read, pid_other, sizeof(int));

write(fd_write, pid_my, sizeof(int));

printf("Recive pid : %dn", pid_other);

}

return 0;

}

版权声明:本站文章来源互联网,如有侵犯您的权益,请及时联系我们处理;

原文链接:https://baike.tt44.com/news/1_494263.html