Попытка создать 2 дочерних процесса и 1 внук, которые запускаются по порядку

Итак, я пытаюсь создать 2 дочерних процесса и один дочерний процесс от первого дочернего процесса. Я пытаюсь запустить первый дочерний процесс, затем внука, а затем второго ребенка с родителем, вызывающим pid, когда процесс завершен. Я полностью застрял - у меня есть множество версий кода, но я не могу заставить их запускаться в правильном порядке. Будем признательны за любую помощь, совет или ссылки.

Желаемый результат будет

-Я первый ребенок

----Я внук

Я родитель, у первого ребенка pid 21505.

-Я первый ребенок, у внука pid 21506

-Попробуйте снова

--Я второй ребенок

-- -->Второй ребенок: передано 1317 байт.

Я снова родитель, у второго ребенка pid 21507.

Родитель-ребенок 21507 выполнено

-Попробуйте снова

**** должны увидеть первые 20 строк файла lab4.c здесь

Родитель - Другой ребенок 21505 выполнено

int main(int* argc, char* args[])
{
pid_t child1, child2, gchild; //process ids
child1 = fork();           //Create the two child processes
if (child1 == 0)
{ // parent
    child2 = fork();
    if (child2 == 0)
    { //parent
        printf("P: first child has pid %d\n", child1);
        printf("P: second child has pid %d\n", child2);

        pid_t wpid; // process id that is finished
        int status; //status code returned by process  
                    //Wait for all child processes to complete
        while ((wpid = wait(&status)) > 0)
        {
            if (wpid > 0)
            {
                printf("P: Child %d is done \n", wpid);
            }
        };

        exit(0); //exit main parent process
    }
    else
    {
        //Second process's code

        printf("SC: I am the second child.\n");
        int totalBytes = 0; //total number of bytes in the file we are going to read in
        char buffer[2056]; //file contents size 2056 bytes
        ssize_t read_bytes = 0; //Bytes from each chunk get placed here temporarily

        ///Read in file contents: home/common/lab_sourcefile
        int fd_in = open("/home/COIS/3380/lab4_sourcefile", O_RDONLY);//open the file
        do
        {
            //read the file chunk by chunk to the buffer
            read_bytes = read(fd_in, buffer, (size_t)2056);

            // End of file or error.
            if (read_bytes <= 0)
            {
                break; //done reading file
            }

            //Save the total number of bytes
            totalBytes = totalBytes + read_bytes;
        } while (1); //infinite loop until we are done reading the file

        //Write out contents to: lab4_file_copy
        char filepath[1024]; //temp path
        getcwd(filepath, sizeof(filepath)); //Get the current working directory
        strcat(filepath, "/lab4_file_copy"); //Tack on the filename
        int fd = open(filepath, O_RDWR | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH); //open the file. O_RDWR = read and write flag, O_CREAT = create if doesnt exist, S_* flags are permission flags from fstat 
        write(fd, buffer, strlen(buffer)); //write to the file

        close(fd_in);//close file we were reading
        close(fd); //close copy file

        // print out the number of bytes the file
        printf("SC: --> Second child: %d bytes transferred.\n", totalBytes);

        exit(0); //done kill second child process
    }
}
else
{
    //First child process

    printf("FC: I'm the first child.\n");

    //Create the granchild process
    gchild = fork();
    if (gchild == 0)
    {
        printf("GC: I am the grandchild.\n");

        sleep(3); //sleep for 3 seconds

        printf("GC: #### Output start ####\n");
        execlp("head", "head", "-n", "20", "l.c", NULL); //this should exit automatically
        printf("ERROR: execlp command failed\n");//This will only run if the execlp process fails
        exit(1); //FAILED!
    }
    else
    {
        //Output the granchild pid
        printf("FC: I am the first child, grandchild has pid %d\n", gchild);
        int grandchildStatus;
        //Wait for grandchild process to be done. Polling...
        while ((waitpid(gchild, &grandchildStatus, WNOHANG)) != gchild)
        {
            printf("FC: Try again\n");
            sleep(1);
        };
        printf("GC: #### Output end ####\n");
        //End of first child. Grandchild must have completed.

        exit(0); //Done. kill first child process
    }
}

}


person sidelaunch    schedule 09.11.2017    source источник
comment
Если вы поменяли местами 3-ю и 4-ю линии, вы могли бы просто синхронизироваться с вызовами wait после каждого форка. Если вы хотите, чтобы они были такими, какие они есть, вам понадобится дополнительный механизм синхронизации. Есть из чего выбирать: конвейеры, сигналы, семафоры с общей памятью и т. д. Выбирайте сами.   -  person PSkocik    schedule 09.11.2017
comment
учить семафоры.   -  person Christian Gibbons    schedule 09.11.2017


Ответы (1)


В вашей программе есть две ошибки:

  • Последняя else часть:

    Вы вызываете fork, поэтому все, что идет после функции fork, будет выполняться в обоих процессах.

    И родитель, и второй дочерний элемент напечатают: "Я родитель, первый дочерний элемент имеет pid..."

    Чтобы исправить это, вам нужно добавить if(child2 == 0) (внутри блока else)...

  • Порядок инструкций:

    Когда вы запускаете дочерний процесс, дочерний процесс на самом деле будет работать в то же время, что и родительский процесс:

    Если один процесс выводит «Hello world.», а другой — «Это тест», вы можете увидеть на экране следующий текст: «Это Hello является миром. test." (или подобным), потому что оба процесса писать на экран одновременно.

    Вы можете использовать функцию waitpid в родительском процессе дочернего процесса, чтобы дождаться завершения дочернего процесса, чтобы гарантировать, что дочерний процесс завершится до того, как родитель продолжит (распечатывая текст).

    Однако если вы хотите сначала напечатать текст в родительском процессе, вам придется найти способ остановить дочерний процесс и дождаться завершения печати родительским процессом.

    Например, вы можете использовать raise(SIGSTOP); для остановки текущего процесса. В другом процессе используйте kill(pid, SIGCONT); для продолжения другого ожидающего процесса pid:

    child = fork();
    if(child == 0)
    {
        raise(SIGSTOP); /* Wait for the parent */
        /* Do something */
    }
    else
    {
        /* Do something */
        kill(child, SIGCONT); /* Tell the child to continue */
    }
    

... однако: Как только что упомянул PSkocik, даже в этом случае ваша программа может зависнуть - так что это не так просто!

person Martin Rosenau    schedule 09.11.2017
comment
Что, если SIGCONT будет отправлен до SIGSTOP? - person PSkocik; 09.11.2017