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

标签 c pipe exec fork osx-mavericks

我正在尝试提升我的程序的权限,将文件写入系统位置。我在 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);
}

最佳答案

好的,我已经开始工作了,所以我会为其他人回答我自己的问题。

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

关于c - 以编程方式使用 OSX authopen 将输出管道输出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26412684/

相关文章:

c - ncurses:窗口颜色不起作用

Angular/如何获取api返回数据

c - 管道、dup2 和 exec()

c - 如何用结构解释这些结果?

python/numpy 生成二进制文件以供 C 读取

c - 当使用字符串变量作为路径时,fopen() 为 null

c - 为什么这段 C 代码(写入 unix 管道)不会无限迭代?

javascript - 按子子嵌套数组的第一个值对 Angular 管道中的对象集合进行排序

Java Runtime.exec 转义字符串中的参数

Apache 服务器中的 Python exec() 权限被拒绝 :/cgi_bin/*. py