2015-11-05 65 views
0

我写过这个C程序来实现popen()。运行代码时出现分段错误。 我曾尝试使用execl()而不是execv(),但得到相同的错误。 请帮助popen实现中的分段错误

#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <unistd.h> 
#include <sys/wait.h> 



#include <sys/syscall.h> 
FILE *popen(const char *command,const char* mode) 
{ 
     FILE *fp; 
     int pipe_fd[2]; 
     pid_t pid; 
         /* Assume child is writing. */ 
     pipe(pipe_fd); 

    if ((pid = vfork()) == 0) {  /* Child of vfork... */ 
      if (mode[0] == 'r') { 
        dup2(pipe_fd[1],1); 
      } 
      else if(mode[0] == 'w') 
        dup2(pipe_fd[0],0); 
      close(pipe_fd[0]); 
      close(pipe_fd[1]); 



      execv(command,""); 
      _exit(127); 
    } 
    if(mode[0] == 'r'){ 
      close(pipe_fd[1]); 
      fp = fdopen(pipe_fd[0],mode); 
    } 
    else if(mode[0] == 'w'){ 
      close(pipe_fd[0]); 
      fp = fdopen(pipe_fd[1],mode); 
    } 
    return fp; 

} 

int main(){ 
     File*fp; 
     fp = popen("ls",'r'); 
} 
+1

'popen'是一个预定义的系统调用。 [开放标准](http://pubs.opengroup.org/onlinepubs/009695399/functions/popen.html)这是第一件事。其次,错误是什么?你是否通过调试器来执行它? – t0mm13b

+0

我想通了......细分故障是由于popen的第二个参数,因为我传递一个字符并尝试使用指针(mode [0])访问其值 – user3660655

回答

0

编译器应该提醒你注意这个代码execv(command,"");, execv不接受字符指针作为第二个参数,只是读 man execv