0
我有下面的代碼,它分叉了兩個新進程,將一個標準輸出的內容保存到一個文件中。它運行得很好並保存文件,但在調用函數中返回以下行(不管它是什麼)後,會引發EXC_BAD_ACCESS錯誤。爲什麼?分叉時引起的錯誤
void test(vector<string> inp,int i){
int fds[2]; // file descriptors
long count; // used for reading from stdout
int fd; // single file descriptor
char c; // used for writing and reading a character at a time
pid_t pid; // will hold process ID; used with fork()
pipe(fds);
// child process #1.
fd = open((inp[i+1]).c_str(), O_RDWR | O_CREAT, 0666);
if (fork() == 0) {
if (fd < 0) {
return;
}
dup2(fds[0], 0);
// Don't need stdout end of pipe.
close(fds[1]);
// Read from stdout...
while ((count = read(0, &c, 1)) > 0)
write(fd, &c, 1); // Write to file.
exit(0);
// child process #2
} else if ((pid = fork()) == 0) {
dup2(fds[1], 1);
// Don't need stdin end of pipe.
close(fds[0]);
// Output contents of the given file to stdout.
char **arguments = getArguments(inp[i]);
execvp(arguments[0], arguments);
perror("execvp failed");
exit(0);
// parent process
} else {
waitpid(pid, NULL, 0);
close(fds[0]);
close(fds[1]);
}
}
這不是C,它使用STL。 – unwind
此代碼過於複雜,並不會按原樣編譯。嘗試將其分解並找到再現錯誤的最簡單版本,然後發佈最少的完整代碼。 – Beta
嘗試以更好的方式管理您的流程。您可能正在嘗試讀取或寫入無效的描述符 – Arunmu