【问题标题】:Pipe output to file using OSX authopen programmatically以编程方式使用 OSX authopen 将输出管道输出到文件
【发布时间】:2023-04-08 19:04:01
【问题描述】:

我正在尝试提升我的程序的权限,将文件写入系统位置。我在 OSX 上的 C 中执行此操作,方法是派生一个使用 authopen 创建和写入文件的子进程。

我可以创建文件,但是我很难向其中写入字符串。从authopen 的手册页中,如果未声明-stdoutpipe,我可以使用-wstdin 指向文件。我不想从stdin 读取数据,但我想将一个常量 str 写入文件。

我发现手册页上对-stdoutpipe 的描述令人困惑,网上也没有关于如何使用此标志的示例。谁能提供任何建议如何做到这一点?

我的代码:

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

【问题讨论】:

    标签: c pipe exec fork osx-mavericks


    【解决方案1】:

    好的,我得到了这个工作,所以我会为其他人回答我自己的问题。

    简而言之,字符串应该由父进程通过管道发送,dup函数方便地将管道的读取端复制到stdin。

    另外,我发现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));
        }
    

    【讨论】:

    • 还要注意 dup2 可以代替 2 次调用 close 和 dup。
    猜你喜欢
    • 2013-05-25
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 2015-07-22
    • 2011-01-20
    • 1970-01-01
    相关资源
    最近更新 更多