Как правильно использовать операторы if else и while с дочерним процессом в C - PullRequest
1 голос
/ 18 октября 2019

Я новичок в C, и я пытался создать программу, которая принимает пользовательское целое число, делает последовательность в зависимости от того, является ли число четным или нечетным.

n / 2, если n четное

3 * n + 1, если n нечетное

Новое число будет вычислено, пока последовательность не достигнет 1. Например, если aпользовательские вводы 35:

35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1

По некоторым причинам мой код не 't работать после оператора сканирования дочернего процесса. Я оставил свой код и пример вывода ниже:

Код:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
pid_t pid;

    int i = 0;
    int j = 0;
    /* fork a child process */
    pid = fork();


    if (pid < 0) { /* error occurred */
        fprintf(stderr, "Fork Failed\n");
        return 1;
    }
    else if (pid == 0) { /* child process */
        printf("I am the child %d\n",pid);


    printf("Enter a value: \n");
    scanf("%d", i);

    while (i < 0) {
        printf("%d is not a positive integer. Please try again.\n", i);
        printf("Enter a value: \n");
        scanf("%d", i);

    }
    // can add a print i here
    while (i != 1) {

        if (i % 2 == 0) { // if the inputted number is even  
            j = i / 2;      
        }

        else {
            j = 3 * i + 1;
        }
    printf("%d", j);    
    } 

}


    else { /* parent process */
        /* parent will wait for the child to complete */
        printf("I am the parent %d\n",pid);
        wait(NULL); // wait(NULL) will wait for the child process to complete and takes the status code of the child process as a parameter

        printf("Child Complete\n");
    }

    return 0;
}

Вывод, который я получаю на терминале в Linux (Debian):

oscreader@OSC:~/osc9e-src/ch3$ gcc newproc-posix.c 
oscreader@OSC:~/osc9e-src/ch3$ ./a.out
I am the parent 16040
I am the child 0
Enter a value: 
10
Child Complete
oscreader@OSC:~/osc9e-src/ch3$

1 Ответ

1 голос
/ 18 октября 2019

Перенос комментариев в полусвязный ответ.

Для ваших звонков на scanf() требуется аргумент-указатель;Вы даете ему целочисленный аргумент. Используйте scanf("%d", &i); - и было бы неплохо проверить, что scanf() возвращает 1, прежде чем проверять результат.

Мой компилятор сообщил мне о вашей ошибке. Почему ваш компилятор тоже не сделал этого? Убедитесь, что вы включили все предупреждения, которые вы можете! Ваш комментарий указывает, что вы используете gcc (или, возможно, clang) - я обычно компилирую с помощью:

gcc -std=c11 -O3 -g -Werror -Wall -Wextra -Wstrict-prototypes …

Действительно, для кода из SO я добавляю -Wold-style-declarations -Wold-style-definitions, чтобы убедиться, что функцииобъявлены и определены правильно. Часто хорошей идеей является добавление -pedantic, чтобы избежать случайного использования расширений GCC.

В цикле вам не нужно j - вам следует изменить и напечатать i.

cz17.c

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    int i = 0;
    pid_t pid = fork();

    if (pid < 0)
    {
        fprintf(stderr, "Fork Failed\n");
        return 1;
    }
    else if (pid == 0)
    {
        printf("I am the child %d\n", pid);

        printf("Enter a value: \n");
        if (scanf("%d", &i) != 1)
        {
            fprintf(stderr, "failed to read an integer\n");
            return 1;
        }

        while (i <= 0 || i > 1000000)
        {
            printf("value %d out of range 1..1000000. Try again.\n", i);
            printf("Enter a value: \n");
            if (scanf("%d", &i) != 1)
            {
                fprintf(stderr, "failed to read an integer\n");
                return 1;
            }
        }

        while (i != 1)
        {
            if (i % 2 == 0)
            {
                i = i / 2;
            }
            else
            {
                i = 3 * i + 1;
            }
            printf(" %d", i);
            fflush(stdout);
        }
        putchar('\n');
    }
    else
    {
        printf("I am the parent of %d\n", pid);
        int status;
        int corpse = wait(&status);
        printf("Child Complete (%d - 0x%.4X)\n", corpse, status);
    }

    return 0;
}

Компиляция:

gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes cz17.c -o cz17 

Пример вывода:

$ cz17
I am the parent of 41838
I am the child 0
Enter a value: 
2346
 1173 3520 1760 880 440 220 110 55 166 83 250 125 376 188 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
Child Complete (41838 - 0x0000)
$
...