В показанном коде много проблем:
Возможнобыть и другие проблемы, которые исправляются мимоходом. Пересмотренный код ниже представляет собой два файла, parent.c
и child.c
. Код предполагает, что программа child
находится в текущем каталоге (поэтому ./child
выполнит ее). Вы запускаете parent
;он создает дочерние процессы.
parent.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
static void forking(void)
{
for (int i = 0; i < 4; i++)
{
pid_t pID = fork();
if (pID == 0)
{
static char *args[] = { "./child", "4", "5", NULL };
execv(args[0], args);
fprintf(stderr, "Failed to execute %s\n", args[0]);
exit(EXIT_FAILURE);
}
else if (pID < 0)
{
fprintf(stderr, "Failed to fork()\n");
exit(EXIT_FAILURE);
}
else
{
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
{
printf("Process %d exited with status 0x%.4X\n", corpse, status);
if (corpse == pID)
break;
}
}
}
}
int main(void)
{
forking();
return 0;
}
child.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if (argc != 3)
{
fprintf(stderr, "Usage: %s number1 number2\n", argv[0]);
exit(EXIT_FAILURE);
}
long number1 = strtol(argv[1], 0, 0);
long number2 = strtol(argv[2], 0, 0);
printf("%ld\n", number1 + number2);
return 0;
}
Строго, код должен проверять, что strtol()
работает, но делаеттак правильно - просто Правильное использование strtol()
? для получения более подробной информации.
Пример вывода
$ ./parent
9
Process 14201 exited with status 0x0000
9
Process 14202 exited with status 0x0000
9
Process 14203 exited with status 0x0000
9
Process 14204 exited with status 0x0000
$