【发布时间】:2017-10-02 04:57:05
【问题描述】:
我正在尝试使用fork() 在 C++ 中反转一个字符串,这样每个进程最多打印一个字符。我的想法是,打印完每个字符后,我fork进入一个新进程,结束父进程,然后继续。这是我的代码:
#include <string>
#include <iostream>
#include <unistd.h>
/*
Recursively print one character at a time,
each in a separate process.
*/
void print_char(std::string str, int index, pid_t pid)
{
/*
If this is the same process,
or the beginning of the string has been reached, quit.
*/
if (pid != 0 || index <= -1)
return;
std::cout << str[index];
if (index == 0)
{
std::cout << std::endl;
return;
}
print_char(str, index-1, fork());
}
int main(int argc, char** argv)
{
std::string str(argv[1]);
print_char(str, str.length()-1, 0);
}
但是,当使用参数“hey”测试代码时,它会打印“yeheyy”。我对fork() 的理解是,它使用内存空间的副本创建了一个重复的进程,每当我在精神上“遍历”代码时,它似乎应该可以工作,但我无法弄清楚我的逻辑在哪里失败。
【问题讨论】:
-
有更好更简单的方法来反转一个字符串。
-
您可能需要使用
wait()或其亲属之一。第一个过程需要派生一个将打印字符串其余部分的子进程,并在打印其字符(和换行符)之前等待它完成。我还会观察到,我想不出我会使用fork()作为函数调用的参数的情况。