以编程方式使用OSX authopen将输出管道输出到文件

时间:2014-10-16 19:48:57

标签: c pipe exec fork osx-mavericks

我正在尝试提升程序的权限,将文件写入系统位置。我在OSX上的C中执行此操作,通过分配使用authopen创建和写入文件的子进程。

我可以创建文件,但是我在编写字符串时遇到了困难。在authopen的手册页中,如果未声明-w,我可以使用stdin-stdoutpipe定向到文件。我不想从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);
}

1 个答案:

答案 0 :(得分:2)

好的,我让这个工作,所以我会回答别人的问题。

简而言之,字符串应由父进程通过管道发送,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));
    }