2014-10-16 59 views
1

我試圖提升程序的權限,將文件寫入系統位置。我在OSX的C上做了這件事,通過分支子進程使用authopen創建並寫入文件。以編程方式使用OSX authopen將文件輸出到文件

我可以創建該文件,但是我很難寫入一個字符串。從authopen的手冊頁中,如果-stdoutpipe未被聲明,我可以使用-w來指示stdin到文件。我不想從stdin讀取,但我想寫一個常量str到文件。

我發現-stdoutpipe的描述混淆了man頁面,並且沒有關於如何使用該標誌的示例。任何人都可以提供任何建議如何做到這一點?

我的代碼:

pid_t processId = fork(); 
if (processId == 0) { 
    //in child process 
    const char * authopenPath = "/usr/libexec/authopen"; 

    //Create the file fromProg if it does not exist. This works OK. 
    execl(authopenPath, 
      authopenPath, 
      "-c", 
      "/etc/fromProg", 
      NULL); 

    //This is where I need help. 
    execl(authopenPath, 
      authopenPath, 
      "-stdoutpipe", //<- Not sure how to write a string to file using this 
      //-w -a",   //<- Or this 
      "/etc/fromProg", 
      NULL); 

    exit(0); 
} 

回答

2

好,我得到這個工作,所以我會回答我自己爲別人的問題。

簡而言之,應該由父進程通過管道發送字符串,並且dup函數可方便地將管道的讀取端複製到標準輸入。

此外,我發現這個參考creating pipes非常有幫助。

int pip[2]; 

    if (pipe(pip) != 0){ 
     //error creating pipe 
     exit(1); 
    } 

    pid_t processId; 
    processId = fork(); 

    if (processId == -1) { 
     //error creating fork 
     exit(1); 
    } 

    if (processId == 0) { 
     //in child process 

     //close write end of pipe 
     close(pip[1]); 

     //close stdin and duplicate the read end of pipe to stdin 
     close(0); 
     dup(pip[0]); 

     //test reading from stdin 
     //char buffer[35]; 
     //read(STDIN_FILENO, buffer, 35); 
     //printf("Received string: %s", buffer); 

     const char * authopenPath = "/usr/libexec/authopen"; 

     execl(authopenPath, 
       authopenPath, 
       "-c","-w","-a", 
       "/etc/fromProg", 
       NULL); 

     exit(0); 
    } 
    else { 
     //in parent process 

     //close read end of pipe 
     close(pip[0]); 

     //write to write end of pipe 
     char string[] = "Helloooo Pipe!\n"; 
     write(pip[1], string, (strlen(string)+1)); 
    } 
+0

另請注意,dup2可以代替2個關閉和重複的調用。 – 2014-10-17 20:51:44

相關問題