写在C管道上

时间:2017-11-27 04:04:16

标签: c pipe

我正在尝试创建一个基本上有2个进程的程序。第一个从用户获取一个字符串并将其传递给另一个。第二个从管道中读取字符串。将其大写然后将其发送回第一个流程。然后打印出2个叮当声。

我的代码确实传递了字符串而另一个进程读取它并将其大写但我认为第二次写入或第二次读取时出错。这是代码:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#define SIZE 15
int main()
{
int fd[2];
pipe(fd);
if(fork() == 0)
{
char message[SIZE];
int length;

close(fd[1]);
length = read(fd[0], message, SIZE);
for(int i=0;i<length;i++){
    message[i]=toupper(message[i]);
    }
printf("%s\n",message);
close(fd[0]);

open(fd[1]);
write(fd[1], message, strlen(message) + 1);
close(fd[1]);
}
else
{

char phrase[SIZE];
char message[SIZE];
printf("please type a sentence : ");
scanf("%s", phrase);
close(fd[0]);
write(fd[1], phrase, strlen(phrase) + 1);
close(fd[1]);

sleep(2);

open(fd[0]);
read(fd[0], message, SIZE);
close(fd[0]);
printf("the original message: %s\nthe capitalized version: 
        %s\n",phrase,message);
}
return 0;
}

1 个答案:

答案 0 :(得分:1)

这是一个双管解决方案的演示......保持&#34; scanf()&#34;你被占用只捕获第一个单词...而不是所有输入:

#include <stdio.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <signal.h>

#define SIZE 15

int main()
{
    int to_child_fd[2];
    int to_parent_fd[2];
    pipe(to_child_fd);
    pipe(to_parent_fd);

    if (fork() == 0) {
    char message[SIZE];
    int length;

    close(to_child_fd[1]);  /* child closes write side of child  pipe */
    close(to_parent_fd[0]); /* child closes read  side of parent pipe */
    length = read(to_child_fd[0], message, SIZE);
    for (int i = 0; i < length; i++) {
        message[i] = toupper(message[i]);
    }
    printf("child: %s\n", message);
    write(to_parent_fd[1], message, strlen(message) + 1);
    close(to_parent_fd[1]);
    } else {

    char phrase[SIZE];
    char message[SIZE];
    printf("please type a sentence : ");
    scanf("%s", phrase);
    close(to_parent_fd[1]); /* parent closes write side of parent pipe */
    close(to_child_fd[0]);  /* parent closes read  side of child  pipe */
    write(to_child_fd[1], phrase, strlen(phrase) + 1);
    close(to_child_fd[1]);

    read(to_parent_fd[0], message, SIZE);
    printf("the original message: %s\nthe capitalized version: %s\n", phrase, message);
    }
    return 0;
}