c - 我怎样才能在同一个管道上写两次?

标签 c linux ubuntu-14.04

我希望父级从标准输入中读取并将其写入管道,然后子级从该管道中读取并将其转换为大写,然后通过另一个管道将其发送回父级,然后父级将其打印在标准输出上,然后写入更多一次。

家长不写作时间

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#define bufsize 200

int main(int argc,char*argv[])
{
    char buf[bufsize];
    char buf2[bufsize];
    int x;
    int child;
    int fd[2];
    int fd1[2];
    int nbytes,mbytes;
    int i,j,k;
    int status=0;

    if(pipe(fd)==-1)
        printf("pipe");
    if(pipe(fd1)==-1)
        printf("pipe");

    switch(fork())
    {
        case -1 : printf("fork");
        case 0:{
            //for(k=1;k<3;k++)
            //{close(fd[1]);
            nbytes = read(fd[0], buf, bufsize);   

            for(i=0;i<=strlen(buf);i++){
                if(buf[i]>=97&&buf[i]<=122)
                buf[i]=buf[i]-32;
            }//end for

            close(fd1[0]);
            write(fd1[1], buf, nbytes);
            _exit(EXIT_SUCCESS);   

        }//end child

        default:{
            for(j=1;j<3;j++){
                close(fd[0]);
                printf("Enter any thing:\n");
                x=read(STDIN_FILENO, buf, bufsize);
                write(fd[1],buf,x);

                close(fd1[1]);
                mbytes = read(fd1[0], buf, bufsize);   
                close(fd1[0]); 
                write(STDOUT_FILENO, buf, mbytes);
            }
            //wait(status);
            exit(EXIT_SUCCESS);
        }//end default
    }//end switch
}

最佳答案

如果您想向同一个管道写入两次,不要在第一次写入后关闭它。仅在完成后关闭它。

关于c - 我怎样才能在同一个管道上写两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37214823/

相关文章:

c++ - 什么是内斜接计算?

linux - 无法使用脚本写入文件

linux - linux下哪个信号可以用来临时挂起进程

php - 多 PHP 如何在 Ubuntu 14.04 上安装带有 PEAR 和扩展的 php 5.3

node.js - Ubuntu 14.04 上的 MEAN 堆栈突然停止工作

c - 我的递归质数函数代码有一些错误

c - 使用一个结构重新散列链式哈希表并调整其大小

c - 遍历数组元素会在数组计数器的最后一个值上产生奇怪的值

python - 在 Python 中通过 Xlib 找出鼠标按钮状态

python - 在 ubuntu 14.04 中使用 python Adafruit_BBIO GPIO 和 ADC 以及 BeagleBone Black 时出错