2015-11-05 33 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