C system calls pipe, fork, and execl

偶尔善良 提交于 2019-12-24 13:55:02

问题


I fork()'d a child process and created pipes between them and am able to send argument argv[1] to the child. I want the child to take that filename provided from argv[1] and perform an execl("/bin/cat","cat",(char *) 0); How do I route the filename piped to the child to the execl?

Enclose is my code for clearity :

int main(int argc, char ** argv){
   int fds[2];
   char buffer[100];
   int status;

   if(pipe(fds) == -1){
      perror("pipe creation failed");
      exit(EXIT_FAILURE);
   }

   switch (fork()){

    case 0://child
       close(fds[1]); //close stdout so can only do stdin
       read(fds[0],buffer,strlen(argv[1]));
       printf("from parent: %s\n",argv[1]);
       execl("/bin/cat","cat",(char*)0);
       perror("cat failed");
       exit(20);
       break;

      case -1: //fork failure
       perror("fork failure");
       exit(EXIT_FAILURE);

      default: //parent 
       close(fds[0]); //close stdin so only can do stdout
       write(fds[1],argv[1], strlen(argv[1]));             
   }   

   return (EXIT_SUCCESS);
}

回答1:


Why are you writing the filename through the pipe when fork() preserves argv[1]?

You're not checking your read length against your buffer length.

You're not transmitting the trailing nul (strlen() doesn't include it) so the filename string's terminator in buffer is uninitialized. Append +1 to all of your strlen() values to correct that. Then,

execl("/bin/cat","cat",buffer,(char*)0);

will do what you ask for, but you've closed stdout so the cat (not the execl) will fail, and you're not checking its exit code.



来源:https://stackoverflow.com/questions/16500247/c-system-calls-pipe-fork-and-execl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!