【发布时间】:2014-06-24 20:25:23
【问题描述】:
我正在尝试使用管道实现一个程序,其中父进程接受一个字符串并将其传递给子进程。只需要单管即可。管道如何读写接受字符串。
这是我的示例代码!全部!
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
using namespace std;
int main()
{
int pid[2];
ssize_t fbytes;
pid_t childpid;
char str[20], rev[20];
char buf[20], red[20];
pipe(pid);
if ((childpid = fork()) == -1) {
perror("Fork");
return(1);
}
if (childpid == 0) {
// child process close the input side of the pipe
close(pid[0]);
int i = -1, j = 0;
while (str[++i] != '\0') {
while(i >= 0) {
rev[j++] = str[--i];
}
rev[j] = '\0';
}
// Send reversed string through the output side of pipe
write(pid[1], rev, sizeof(rev));
close(pid[0]);
return(0);
} else {
cout << "Enter a String: ";
cin.getline(str, 20);
// Parent process closing the output side of pipe.
close(pid[1]);
// reading the string from the pipe
fbytes = read(pid[0], buf, sizeof(buf));
cout << "Reversed string: " << buf;
close(pid[0]);
}
return 0;
}
【问题讨论】:
-
rev、red、str、buf的用途是什么?看起来这些混淆的名称是造成问题的原因。 -
是的,一切都好!请问您有什么特别的问题?
-
为什么标记为 C?
标签: c++ unix pipe named-pipes