Properly close pipe handles when work is done

This commit is contained in:
Benny Baumann 2020-09-15 22:07:52 +02:00 committed by cgzones
parent 6921000481
commit 443a943798
1 changed files with 14 additions and 3 deletions

View File

@ -53,18 +53,21 @@ void OpenFilesScreen_draw(InfoScreen* this) {
static OpenFiles_ProcessData* OpenFilesScreen_getProcessData(pid_t pid) { static OpenFiles_ProcessData* OpenFilesScreen_getProcessData(pid_t pid) {
OpenFiles_ProcessData* pdata = xCalloc(1, sizeof(OpenFiles_ProcessData)); OpenFiles_ProcessData* pdata = xCalloc(1, sizeof(OpenFiles_ProcessData));
OpenFiles_FileData* fdata = NULL;
OpenFiles_Data* item = &(pdata->data); int fdpair[2] = {0, 0};
int fdpair[2];
if (pipe(fdpair) == -1) { if (pipe(fdpair) == -1) {
pdata->error = 1; pdata->error = 1;
return pdata; return pdata;
} }
pid_t child = fork(); pid_t child = fork();
if (child == -1) { if (child == -1) {
close(fdpair[1]);
close(fdpair[0]);
pdata->error = 1; pdata->error = 1;
return pdata; return pdata;
} }
if (child == 0) { if (child == 0) {
close(fdpair[0]); close(fdpair[0]);
dup2(fdpair[1], STDOUT_FILENO); dup2(fdpair[1], STDOUT_FILENO);
@ -80,12 +83,17 @@ static OpenFiles_ProcessData* OpenFilesScreen_getProcessData(pid_t pid) {
exit(127); exit(127);
} }
close(fdpair[1]); close(fdpair[1]);
OpenFiles_Data* item = &(pdata->data);
OpenFiles_FileData* fdata = NULL;
FILE* fd = fdopen(fdpair[0], "r"); FILE* fd = fdopen(fdpair[0], "r");
for (;;) { for (;;) {
char* line = String_readLine(fd); char* line = String_readLine(fd);
if (!line) { if (!line) {
break; break;
} }
unsigned char cmd = line[0]; unsigned char cmd = line[0];
if (cmd == 'f') { if (cmd == 'f') {
OpenFiles_FileData* nextFile = xCalloc(1, sizeof(OpenFiles_FileData)); OpenFiles_FileData* nextFile = xCalloc(1, sizeof(OpenFiles_FileData));
@ -101,15 +109,18 @@ static OpenFiles_ProcessData* OpenFilesScreen_getProcessData(pid_t pid) {
free(line); free(line);
} }
fclose(fd); fclose(fd);
int wstatus; int wstatus;
if (waitpid(child, &wstatus, 0) == -1) { if (waitpid(child, &wstatus, 0) == -1) {
pdata->error = 1; pdata->error = 1;
return pdata; return pdata;
} }
if (!WIFEXITED(wstatus)) if (!WIFEXITED(wstatus))
pdata->error = 1; pdata->error = 1;
else else
pdata->error = WEXITSTATUS(wstatus); pdata->error = WEXITSTATUS(wstatus);
return pdata; return pdata;
} }