gpt4 book ai didi

c - 管道和 waitpid

转载 作者:行者123 更新时间:2023-11-30 17:32:23 27 4
gpt4 key购买 nike

我的管道有问题。我浏览了这些主题,但没有找到任何可以解决我的问题的内容。

我的管道工作正常,但我想知道我的 child 何时终止。所以我想用waitpid来检查我的 child 。但这是行不通的。

我的管道:

int interpretiere_pipeline(Kommando k){

int pipe1[] = { -1, -1 };
int pipe2[] = { -1, -1 };

int status, pid, laenge, i;
Kommando command;
Liste l;

i = 0;
status = 0;
laenge = k->u.sequenz.laenge;

l = k->u.sequenz.liste;


printf("Anzahl der Elemente der Pipe: %i!\n", laenge);

while(i < laenge) {
pipe2[0] = pipe1[0];
pipe2[1] = pipe1[1];
command = (Kommando) listeKopf(l);

if (i > 0) {
close(pipe2[1]);
}

if (pipe(pipe1) < 0) {
perror("Pipe-Fehler");
exit(1);
}
/* fuehre Kindprozesse aus -> speichere pid */
pid = fork();

switch (pid) {
case -1:
/* Fehler bei Fork -> Abbruch */
perror("fork-Fehler");
exit(1);
case 0:
/* Leseströme umlegen auf vorherigen Prozess (außer beim ersten Prozess) */
if (pipe2[0] != -1) {
if(dup2(pipe2[0], STDIN_FILENO) == -1){
perror("dup2 failed\n");
exit(1);
}
}

/* Schreibströme umlegen auf nachfolgenden Prozess (außer beim letzten Prozess) */
if (i < laenge - 1) {
if(dup2(pipe1[1], STDOUT_FILENO) == -1){
perror("dup2 failed\n");
exit(1);
}
}

/* fuehre Kommandos aus */
interpretiere_einfach(command, 0);
exit(1);
break;
default:
/* schreibe Prozesse in die Struktur */
printf("Name : %s\n",command->u.einfach.worte[0]);
pGlobal = erzeugeProzess( pid, "test", "RUNNING");
/* fuege Struktur in Liste ein */
procTable = listeAnfuegen(procTable, &pGlobal);
/* Zaehler fue while-Schleife*/
i++;

sleep(2);
break;
}
l = listeRest(l);
}

return status;
}

我的等待进程

          waitpid(pid, &kind_status, 0);
if(WIFEXITED(kind_status)){
printf("Kind mit der PID %d wurde beendet\n",pid);
if (WEXITSTATUS(kind_status) == 0) {
/** setze status exit(0) */
/*printf("Kind erfolgreich\n");*/
p->status = "exit(0)";
}
/* nicht erfolgreiche ausgeführt */
else
{
/** setze status exit(1) */
/*printf("Kind nicht erfolgreich\n");*/
p->status = "exit(1)";
}
}
else if(WIFSIGNALED(kind_status)){
/*printf("Kind mit der PID %d wurde durch Signal abgebrochen. Signalnummer: %d\n",pid, WTERMSIG(kind_status));*/
p->status = "signal";
}
i = listeLaenge(procTable);
procTable = listeAnfuegen(procTable, p);
/*procTable = listeAnfuegen(procTable, &pGlobal);*/
if(listeLaenge(procTable) <= i) {
fprintf(stderr, "Fehler beim Schreiben in die Liste!");
}

我可以将它放在管道下方,并与管道的长度成一个环吗?

最佳答案

无论你怎么做,你都必须将所有子 pid 存储在某种列表中。所以我建议,你做一个循环:

while( /* there are processes to be waited for */ ) {
pid_t deadpid = waitpid( -1, &kind_status, 0 );
/* handle kind_status and remove deadpid from the list */
}

关于c - 管道和 waitpid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24208665/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com