正确分叉 N child 个进程
Forking N child processes properly
所以我正在编写一个简单的纸牌游戏。我需要创建 3、4 或 5 个流程,其中 parent 充当发牌员将牌交给他们。我遇到了一个意想不到的错误,我不知道如何处理。
我得到的输出是:
15019373x-apollo:/home/15019373x/comp2432/lab3$ ./rummy 3
Child: 1 PID 26581
Child: 2 PID 26582
Child: 3 PID 26585
15019373x-apollo:/home/15019373x/comp2432/lab3$ Child: 2 PID 26584
Child: 3 PID 26586
Child: 3 PID 26583
Child: 3 PID 26587
所以我试图创建 3 个进程,但循环似乎创建了 7 个。我不太确定发生了什么。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int players = atoi(argv[1]);
char deck[52][3];
int i, pid, cid;
if (players > 5 || players < 3)
{
printf("%d is not the allowed number of players, min is 3 and max is 5\n", players);
exit(1);
}
for (i = 0; i < argc - 2; i++)
{
strcpy(deck[i], argv[i+2]);
}
for (i = 0; i < players; i++)
{
pid = fork();
if (pid < 0)
{
printf("Fork Failed\n");
exit(1);
}
else if (pid == 0)
{
printf("Child: %d PID %d\n", i+1, getpid());
}
}
}
如果有人能指出正确的方向,我将不胜感激。
非常感谢!
记住 children also 继续执行 for
循环和 fork
more children.
作为一个简单的修复(因为您显然仍在开发此程序),请在 child 代码中的 printf
之后调用 exit()
。您不希望 children 继续执行仅供 parent 至 运行 的代码。
所以我正在编写一个简单的纸牌游戏。我需要创建 3、4 或 5 个流程,其中 parent 充当发牌员将牌交给他们。我遇到了一个意想不到的错误,我不知道如何处理。
我得到的输出是:
15019373x-apollo:/home/15019373x/comp2432/lab3$ ./rummy 3
Child: 1 PID 26581
Child: 2 PID 26582
Child: 3 PID 26585
15019373x-apollo:/home/15019373x/comp2432/lab3$ Child: 2 PID 26584
Child: 3 PID 26586
Child: 3 PID 26583
Child: 3 PID 26587
所以我试图创建 3 个进程,但循环似乎创建了 7 个。我不太确定发生了什么。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int players = atoi(argv[1]);
char deck[52][3];
int i, pid, cid;
if (players > 5 || players < 3)
{
printf("%d is not the allowed number of players, min is 3 and max is 5\n", players);
exit(1);
}
for (i = 0; i < argc - 2; i++)
{
strcpy(deck[i], argv[i+2]);
}
for (i = 0; i < players; i++)
{
pid = fork();
if (pid < 0)
{
printf("Fork Failed\n");
exit(1);
}
else if (pid == 0)
{
printf("Child: %d PID %d\n", i+1, getpid());
}
}
}
如果有人能指出正确的方向,我将不胜感激。
非常感谢!
记住 children also 继续执行 for
循环和 fork
more children.
作为一个简单的修复(因为您显然仍在开发此程序),请在 child 代码中的 printf
之后调用 exit()
。您不希望 children 继续执行仅供 parent 至 运行 的代码。