Я пишу программу C, которая будет запускать команды Linux, например:
$ кошка /etc/passwd | вырезать -f1 -d: | Сортировать
в ожидании завершения дочернего процесса только один дочерний процесс завершается успешно. Код зависает, отображая "текущую сортировку"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
int main()
{
int i,fd1[2],fd2[2],status,listpid[3];
pid_t child;
pipe(fd1);
pipe(fd2);
for(i=0; i< 3; i++)
{
printf("\ncreating child\n");
if((child = fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if(child == 0)
{
if(i == 0)
{
close(1); dup(fd1[1]);
close(fd1[0]);
close(fd1[1]);
printf("\nrunning cat /etc/passwd\n");
fflush(stdout);
execlp("cat","cat","/etc/passwd", (char *)NULL);
exit(EXIT_SUCCESS);
}
else if(i == 1)
{
close(0); dup(fd1[0]);
close(fd1[1]);
close(fd1[0]);
close(1); dup(fd2[1]);
close(fd2[1]);
close(fd2[0]);
printf("\nrunning cut -f1 -d:\n");
fflush(stdout);
execlp("cut","cut","-f1","-d:", (char *)NULL);
exit(EXIT_SUCCESS);
}
else if(i == 2)
{
close(0); dup(fd2[0]);
close(fd2[1]);
close(fd2[0]);
close(fd1[0]);
close(fd1[1]);
printf("\nrunning sort\n");
fflush(stdout);
execlp("sort","sort", (char *)NULL);
exit(EXIT_SUCCESS);
}
}
else
{
listpid[i]=child;
}
}
close(fd1[0]);
close(fd1[1]);
close(fd2[0]);
close(fd2[1]);
for(i = 0; i < 2; i++)
{
waitpid(listpid[i], &status, 0);
if(WIFEXITED(status))
{
printf("\n[%d] TERMINATED (Status: %d)\n",listpid[i], WEXITSTATUS(status));
}
}
exit(EXIT_SUCCESS);
}