1
我想讓我的父進程在運行authopen
的子分支上等待寫入具有提升特權的文件。父項中的wait/waitpid
將無限期掛起以終止子進程。我相信這是因爲authopen
在程序退出之前不會釋放該文件。C父進程無限期地等待分叉的子進程運行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;
}
後你'DUP(PIP [0])'你應該'接近(PIP [0])' – 2014-12-04 00:37:21
但更重要的是,父母需要關閉畫中畫[1],因爲孩子可能是阻塞從管道讀取。 – 2014-12-04 00:38:39
是的,'authopen'不會退出,直到它的標準輸入接收到EOF爲止。 – 2014-12-04 00:39:11