1. 业奇农业网 > 资讯 >

Linux管道实验题

<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://nongye.s666.cn/news/1_657494263.html