过程控制

时间:2012-09-17 06:19:16

标签: c++ c unix fork

所以我正在尝试编程,这里是:

Write a C/C++ program (call it string invert) that takes a
string argument from the command line and outputs the string in reversed order. Here comes
the twist: Each process can output at most one character. If you want to output more than a
single character, you must fork off one or more processes in order to do that, and each of the
forked processes in turn outputs a single character. After the call to program string invert
with the command line argument, the output should appear, and no more processes should
be running, in addition to the shell. Test your program on any UNIX/LINUX machine, and
turn in the source code as part of the written assignment. (The source code should be at
most a few lines long.)

我可以轻松读取和反转字符串,没问题。问题在于它说“每个进程最多只能输出一个字符”是什么意思。我甚至不明白这意味着什么。我不需要任何代码,我相信一旦理解我就可以自己做。我只需要有人来解释那应该是什么意思。

2 个答案:

答案 0 :(得分:2)

假设您输入“abcd”,那么您的程序应该为每个字符生成一个进程。所以第一个过程将返回'd',第二个过程将返回'c',依此类推。这项任务可能是对你理解同步过程的程度的一种考验。

答案 1 :(得分:1)

每个进程都应该打印 ONE 字符。例如:

$yourProgamm sample

通常你会遍历样本字符串,只需调用cout左右来打印每个字符。但是,您应该只为每个进程打印一个字符。意思是输出e,一切都很好。但是如果再次运行循环以输出l,则相同的进程会打印第二个字符。

因此,您必须 fork 每个字符的进程,让该进程打印一个字符并继续循环。一定要与join同步,否则你可能会得到随机顺序输出(我想这是作业的主要部分,只是运行它几次没有看到我的意思)。