我正在尝试让我的父进程等待运行authopen
的子fork,以编写具有提升权限的文件。父级中的wait/waitpid
无限期挂起,以便子进程终止。我相信这是因为authopen
在程序退出之前不会释放文件。
authopen
写入的文件在程序生命周期内被锁定,因此无法读取文件,无法使用其他authopen
进程写入文件,并在例如打开文件中打开文件。在程序退出之前,vim不会显示文件的内容。
首先,我想了解这里发生了什么。当execl
完成时,它不应该还释放所有资源吗?
其次,我想要一些解决方案。
以下是演示此问题的程序。
我的平台是OSX。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, const char * argv[]) {
int pip[2];
if (pipe(pip) != 0) exit(1); //error creating pipe
pid_t processId;
processId = fork();
if (processId == -1) exit(1); //pipe error
if (processId == 0) { //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]);
//run authopen
const char * authopenPath = "/usr/libexec/authopen";
execl(authopenPath, authopenPath, "-c","-w","/usr/local/authopenTest.txt",NULL);
_exit(1); //exec* does not return in case of success.
}
else { //parent process
//close 'read end' of pipe
close(pip[0]);
//write to 'write end' of pipe
char * cstr = "write this to file...";
write(pip[1], cstr, (strlen(cstr)));
int status;
//waitpid(0, &status, WNOHANG); //this is ok, but doesn't block on child completing
int p_id = wait(&status); //PROBLEM: this hangs indefinitely. Why?
if(p_id != -1) {
printf("Exit status %d\n", status);
}
}
return 0;
}
答案 0 :(得分:1)
完成写入后,您需要关闭管道。否则,读者继续等待更多数据。例如:
write(pip[1], ...);
close(pip[1]);
wait(...);