Domanda

I'm a student and am trying to write a simple program for learning purposes. I wrote the following program:

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

int main()
{

     pid_t pid;

     pid = fork();
     if(pid < 0) 
     {
         fprintf(stderr,"Fork failed\n");
         return -1;
     }

     if(pid > 0) 
     { 
         printf("parent\n");
     }

     if(pid == 0) 
     { 

         char* args[] = {"/usr/bin/tr","[:lower:]","[:upper:]", NULL };
             execvp("/usr/bin/tr",args);
         fprintf(stderr,"Error in exec\n");
     }
     return 0;
  }

But I cannot even run this simple program. The output I get is:

 parent
 /usr/bin/tr: read error: Input/output error

Cannot tr get input from the standard input when it is run with execv? Please help.

È stato utile?

Soluzione

Your problem is that the parent process has terminated and closed stdin.

Add

wait(pid);

to the parent code to make it wait for the child to exit.

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