空调系统调用管道,叉和EXECL [英] C system calls pipe, fork, and execl

查看:156
本文介绍了空调系统调用管道,叉和EXECL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我fork()的倒是一个子进程,并在它们之间建立管道和我能够参数ARGV发[1]给孩子。我希望孩子采取从argv的提供该文件名[1],并执行execl的(/斌/猫,猫,(字符*)0);
我怎么路线输送到孩子到execl的文件名?

附上我的code为clearity:

  INT主(INT ARGC,字符** argv的){
   INT FDS [2];
   炭缓冲器[100];
   INT状态;   如果(管(FDS)== -1){
      PERROR(管子创建失败);
      出口(EXIT_FAILURE);
   }   开关(叉())​​{    案件0://子
       关闭(FDS [1]); //关闭标准输出所以只能做标准输入
       读(FDS [0],缓冲液,strlen的(的argv [1]));
       的printf(从父项:%S \\ N的argv [1]);
       EXECL(/斌/猫,猫,(字符*)0);
       PERROR(猫失败);
       出口(20);
       打破;      案例-1:// fork失败
       PERROR(fork失败);
       出口(EXIT_FAILURE);      默认://父
       关闭(FDS [0]); //关闭标准输入所以唯一能做的标准输出
       写(FDS [1],ARGV [1]的strlen(ARGV [1]));
   }   回报(EXIT_SUCCESS);
}


解决方案

为什么要通过管道写文件名时叉() preserves 的argv [1]

你不检查你的读长对你的缓冲区长度。

您不是发射尾随NUL(的strlen()不包括),这样的文件名字符串在终止缓存未初始化。追加 +1 所有的的strlen()值来纠正。然后,

  EXECL(/斌/猫,猫,缓冲,(字符*)0);

会做你问什么,但你已经关闭标准输出所以(不是 EXECL )会失败,而你没有检查它的退出code。

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);
}

解决方案

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.

这篇关于空调系统调用管道,叉和EXECL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆