问题描述
我正在尝试使用管道实现程序,其中父进程接受一个字符串并将其传递给子进程.仅需单个管道即可完成.管道如何读取&写接受字符串.
I m trying to implement a program using pipes where parent process accepts a string and passes it to child process. Need to be done with only single pipe. How does the pipe read & write accepts string.
这是我的示例代码!全部!
Here is my sample code! all!
#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;
}
推荐答案
您永远不会将要反转的字符串传递给子级,因此它会反转一些随机垃圾并将其发送给父级.
You never pass the string to be reversed to the child, so it reverses some random garbage and sends it to the parent.
次要问题:
write(pid[1], rev, sizeof(rev));
close(pid[0]); // Should be pid[1]
return(0); // Should be _exit(0)
您不想在孩子中从main
退出return
的原因是,您不知道会有什么后果.您可以调用退出处理程序来处理父母希望保持完整状态的现实世界对象.
The reason you don't want to return
from main
in the child is that you don't know what consequences that will have. You may call exit handlers that manipulate real world objects that the parent expects to remain intact.
这篇关于使用管道的IPC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!