2017-09-06 2 views
1

J'utilise quelque chose appelé rssgossip.py pour chercher une expression dans les flux rss de mon choix.Mon programme ne semble pas se terminer; Pourquoi?

Fondamentalement, je itère à travers un tableau de flux RSS que je veux rechercher, et chaque fois que je suis forking le processus et en appelant execle() sur le processus enfant. J'obtiens la sortie appropriée, mais ça a l'air bizarre et mon terminal attend juste après que tout soit imprimé.

code

#include <stdio.h> 
    #include <errno.h> 
    #include <unistd.h> 
    #include <string.h> 

    int main(int argc, char *argv[]) { 
     char *feeds[] = {"http://feeds.washingtonpost.com/rss/lifestyle", 
        "http://feeds.washingtonpost.com/rss/world", 
        "http://feeds.washingtonpost.com/rss/opinions"}; 

     int num_feeds = 3; 
     if(argc < 2) { 
      fprintf(stderr, "You need to tell me a search phrase.\n"); 
      return 1; 
     } 
     char *phrase = argv[1]; // this will be the phrase you to search for in the rss feed, passed as an argument 
    printf("we are going to search for \"%s\"\n", phrase); 
    int i; 
    for(i = 0; i < num_feeds; i ++) { 
     char var[255]; 
     sprintf(var, "RSS_FEED=%s", feeds[i]); 
     printf("we are going to search this feed: %s\n", var); 
     char *my_env[] = {var, NULL}; 
     // I believe that once we call execle, the while loop stops because we've totally replaced the process! (we need fork...) 
     pid_t pid = fork(); 
     printf("pid: %d\n", pid); 
     if(pid == -1) { // -1 indicates that fork() had a problem cloning the process 
      fprintf(stderr, "Can't fork process: %s\n", strerror(errno)); 
      return 1; 
     } 
     if(pid == 0) { // isn't a non-zero number for the parent process?? NO, this is like pid==0, i.e. child process 
      printf("running a child process now\n"); 
      if(execle("/usr/bin/python", "/usr/bin/python", 
        "./rssgossip/rssgossip.py", phrase, NULL, my_env) == -1) { 
       fprintf(stderr, "Can't run script: %s\n", strerror(errno)); 
       return 1; 
      } 
     } 
    } 

    return 0; 
} 

Sortie

aarons-MacBook-Pro:ch9 aaronparisi$ ./news hi 
we are going to search for "hi" 
we are going to search this feed: RSS_FEED=http://feeds.washingtonpost.com/rss/lifestyle 
pid: 68853 
we are going to search this feed: RSS_FEED=http://feeds.washingtonpost.com/rss/world 
pid: 68854 
we are going to search this feed: RSS_FEED=http://feeds.washingtonpost.com/rss/opinions 
pid: 0 
running a child process now 
pid: 0 
running a child process now 
pid: 68855 
pid: 0 
running a child process now 
aarons-MacBook-Pro:ch9 aaronparisi$ U.S. general in Afghanistan apologizes for highly offensive leaflets 
How Burma's Rohingya crisis went from bad to worse 
Sir Richard Branson is riding out Hurricane Irma in the wine cellar on his private island 
Britains royal family announces third pregnancy for Duke and Duchess of Cambridge 
Fashion is finally figuring out diversity in ways that actually matter 
The Salt Line is an instant hit, with superb seafood and a view to match 
The 2017 Washington Post Travel photo contest winners and finalists 
Ask Amy: New hire struggles with workplace racism 
Hints From Heloise: Kitchen creativity 
Miss Manners: Helping a young child deflect questions 
A laughing matter 
History shows us how calamitous the North Korea crisis could become 
These Washington players didnt just stick to their college major 
The only thing less fair than the electoral college is the scoring in tennis 
With DACA, Jeff Sessions bent Trump to his will - again 
Washington Post's Scott Wilson is out as national editor 
Who first said, 'The best government is that which governs least'? Not Thoreau. 

Comme vous pouvez le voir, il n'y a pas l'invite de commandes à la fin, et mon terminal est juste assis là, attendant. Pourquoi? Il semble également étrange que l'invite de commande s'affiche avant d'imprimer l'un des articles correspondants, pas sûr pourquoi cela se produit non plus.

Répondre

2

Votre programme est déjà terminé, mais il est difficile de le voir car les processus enfants bifurqués continuent à produire des résultats par la suite.

Regardez au milieu de votre relevé de notes:

running a child process now 
aarons-MacBook-Pro:ch9 aaronparisi$ U.S. general in Afghanistan apologizes for highly offensive leaflets 

Vous pouvez voir que votre shell a affiché une invite au milieu de votre sortie, au moment où le programme initial terminé, mais alors que les processus enfants sont toujours en cours d'exécution.

Si vous appuyez simplement sur [ENTER] une fois la sortie terminée, vous verrez que votre shell est en train d'écouter et vous recevrez immédiatement une autre invite du shell.

Si vous préférez que votre programme ne quitter qu'après tous les processus enfants sont faits, vous devez utiliser wait (2) pour les attendre à la fin: http://man7.org/linux/man-pages/man2/waitpid.2.html

Depuis les retours d'attente -1 si votre processus n'a pas d'enfants, vous pouvez simplement l'appeler dans une boucle jusqu'à ce qu'il le fait:

int status = 0; 
while ((wpid = wait(&status)) > 0); 

(j'ai eu cette formule spécifique de Make parent wait for all child processes.)

+0

problèmes avec cela, il dit attendre prend un int * pas un int? –

+0

@ A.Pizzle Voir ma réponse étendue pour savoir comment utiliser la fonction d'attente. Quand je dis "wait (2)", c'est une façon standard de dire "la fonction wait(), qui est documentée dans la section 2 des pages de manuel". Je ne suis pas sûr si ce jargon spécifique est considéré comme standard sur SO ou pas, désolé pour la confusion. Plus précisément, l'argument int * est un pointeur sur un int où wait() mettra le statut de sortie de l'enfant qui a quitté (et le pid de l'enfant sera renvoyé par wait().) –

+0

Ah ok; ça marche, merci beaucoup! –