【问题标题】:Inverting a string using `fork()`使用 `fork()` 反转字符串
【发布时间】: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() 作为函数调用的参数的情况。

标签: c++ process fork


【解决方案1】:

看来,你的代码没问题,但是cout有问题。

尝试只更改输出行

std::cout << str[index];

std::cout << str[index] << std::flush;

试过了,对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    相关资源
    最近更新 更多