我正在尝试提升我的程序的权限,将文件写入系统位置。我在 OSX 上的 C 中执行此操作,方法是派生一个使用 authopen
创建和写入文件的子进程。
我可以创建文件,但是我很难向它写入字符串。从 authopen
的手册页中,如果 -stdoutpipe
是,我可以使用 -w
将 stdin
定向到文件没有宣布。我不想从 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/