Project

General

Profile

Bug #19837 » wait_bug.c

kjtsanaktsidis (KJ Tsanaktsidis), 08/11/2023 12:53 AM

 
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

void *wait_in_thread(void *arg) {
pid_t pid;
int r;

pid = *((pid_t *)arg);
int status;
printf("waiting for long process (%d) in thread\n", pid);
waitpid(pid, &status, 0);
return NULL;
}

int main(int argc, char **argv) {
pid_t long_pid, short_pid;
pthread_t waitth;
int pipefds[2];
char buf[1];
int status;
int r;

r = pipe(pipefds);
if (r == -1) {
perror("pipe failed");
exit(1);
}

long_pid = fork();
if (long_pid == -1) {
perror("fork failed");
exit(1);
}
else if (long_pid == 0) {
close(pipefds[1]);
printf("long process (%d) starting\n", getpid());
read(pipefds[0], buf, 1);
printf("long process (%d) exiting\n", getpid());
exit(0);
}

short_pid = fork();
if (short_pid == -1) {
perror("fork failed");
exit(1);
}
else if (short_pid == 0) {
close(pipefds[1]);
printf("short process (%d) starting\n", getpid());
usleep(1000000);
printf("short process (%d) exiting\n", getpid());
exit(0);
}

r = pthread_create(&waitth, NULL, wait_in_thread, &long_pid);
if (r != 0) {
printf("pthread_create failed: %d\n", r);
exit(1);
}

usleep(500000);
printf("waiting for any process\n");
r = waitpid(-1, &status, 0);
printf("waitpid returned: (%d, %d)\n", r, status);
return 0;
}
(1-1/2)