Итак, я пытаюсь создать 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
}
}
}
wait
после каждого форка. Если вы хотите, чтобы они были такими, какие они есть, вам понадобится дополнительный механизм синхронизации. Есть из чего выбирать: конвейеры, сигналы, семафоры с общей памятью и т. д. Выбирайте сами. - person PSkocik   schedule 09.11.2017