Domanda

I'm playing with the fork() and system() commands and when I run this example code I find that the child process doesn't print the "Song complete..." line after the system call is finished. Is this normal or have I missed something?

I thought system() would have finished its work then returned to the child process and gone on its merry way to either exit or do additional tasks. That doesn't happen for this code example.

     #include <sys/types.h> /* pid_t */
     #include <sys/wait.h>  /* waitpid */
     #include <stdio.h>     /* printf, perror */
     #include <stdlib.h>    /* exit */
     #include <unistd.h>    /* _exit, fork */

     int main(void)
     {
       pid_t pid;
       int i;
       pid = fork();

       if (pid == -1) {
          /*
           * When fork() returns -1, an error happened.
           */
          perror("fork failed");
          exit(EXIT_FAILURE);
       }
       else if (pid == 0) {
          /*
           * When fork() returns 0, we are in the child process.
           */
          printf("Hello from the child process!\n");
            system("aplay ./SOS_sample.wav");
          printf("Song complete...");
          _exit(EXIT_SUCCESS);  /* exit() is unreliable here, so _exit must be used */
       }
       else {
          /*
           * When fork() returns a positive number, we are in the parent process
           * and the return value is the PID of the newly created child process.
           */
          int status;
            printf("Waiting on the song to end...\n");
            for (i = 0;i<10;i++){
                    printf("%d\n",i);
                    }
          (void)waitpid(pid, &status, 0);
            for (i=0;i<10;i++){
                    printf("%d\n",i);
                    }
       }
       return EXIT_SUCCESS;
     }
È stato utile?

Soluzione

Probably because printf buffers your message, and does not immediatly output it on the standard output. In this case, as your child process gets killed right after, your call to printf would get totally unnoticed.

Try adding a \n at the end of your message to force printf to flush his internal buffer :

printf("Song complete...\n");

Altri suggerimenti

There are two parts to the problem.

  1. You use printf() and don't terminate the message with a newline.
  2. You use _exit() which deliberately avoids flushing buffered output on open file streams (such as standard output).

The basic fix is simple — as accurately diagnosed by Halim Qarroum in his answer:

  1. Include the newline in the output message.
  2. If you can't include the newline, include fflush(stdout) or flush(0).
  3. Or use exit() instead of _exit().

Each of these will cure the missing message. As a general rule, if you want a message to appear, end it with a newline. If you don't, make sure it is produced with fflush(), or ensure that exit() is used to flush the buffers.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top