Project

General

Profile

Bug #1199 » 1199.c

Tai Dinh, 10/03/2019 03:43 PM

 
1
#include <unistd.h>
2
#include <sys/types.h>
3
#include <sys/wait.h>
4
#include <sys/prctl.h>
5
#include <stdio.h>
6
#include <string.h>
7
#include <stdlib.h>
8
#include <fcntl.h>
9
#include <errno.h>
10
#include <pthread.h>
11

    
12
#define TRACEPOINT_DEFINE
13
#define TRACEPOINT_PROBE_DYNAMIC_LINKAGE
14
#include "ust_pipe_and_fork.h"
15

    
16
void *do_thread(void *arg) {
17
	int id = *((int *) arg);
18
	int stdout_pipe[2];
19
	int stderr_pipe[2];
20
	if (pipe(stdout_pipe) || pipe(stderr_pipe)) {
21
		printf("[Thread %d]: pipe failed\n", id);
22
		exit(1);
23
	} else {
24
		fcntl(stdout_pipe[0], F_SETFD, FD_CLOEXEC);
25
		fcntl(stdout_pipe[0], F_SETFD, FD_CLOEXEC);
26
	}
27

    
28
	tracepoint(taidinh, ust_pipe_and_fork, id, "Starting to fork now");
29
	pid_t pid = fork();
30
	if (pid < 0) {
31
		printf("[Thread %d]: Fork failed", id);
32
		exit(1);
33
	}
34
	if (pid > 0) {
35
		//Parent
36
		close(stdout_pipe[1]);
37
		close(stderr_pipe[1]);
38
		sleep(1);
39
		close(stdout_pipe[0]);
40
		close(stderr_pipe[0]);
41
		int ret;
42
		tracepoint(taidinh, ust_pipe_and_fork, id, "Waiting for child");
43
		printf("[Thread %d]: Waiting for child\n", id);
44
		waitpid(pid, &ret, 0);
45
		printf("[Thread %d]: Child exit with %d\n", id, ret);
46
		tracepoint(taidinh, ust_pipe_and_fork, id, "Child exit");
47
	} else {
48
		tracepoint(taidinh, ust_pipe_and_fork, id, "Child starting...");
49
		//Child
50
		setpgid(0, 0);
51
		if (prctl(PR_SET_PDEATHSIG, SIGHUP, 0, 0, 0)) {
52
			fprintf(stderr, "[Thread %d]: Failed to set PDEATHSIG, %s\n", id, strerror(errno));
53
		}
54
		close(1);
55
		dup2(stdout_pipe[1], 1);
56
		close(stdout_pipe[1]);
57
		close(2);
58
		dup2(stderr_pipe[1], 2);
59
		close(stderr_pipe[1]);
60

    
61
		char *argv[3];
62
		argv[0] = strdup("sleep");
63
		argv[1] = strdup("1");
64
		argv[2] = 0;
65
		tracepoint(taidinh, ust_pipe_and_fork, id, "excecvp now...");
66
		execvp(argv[0], argv);
67
		printf("[Thread %d]: Should not ended here\n", id);
68
	}
69
}
70

    
71
int main() {
72
	int i;
73
	int round = 1;
74
	pthread_t workers[10];
75
	int index[10];
76
	while(1) {
77
		printf("--------------------[ %d ]---------------------------\n", round);
78
		printf("Creating workers\n");
79
		for (i = 0; i < 10; i++) {
80
			index[i] = i;
81
			pthread_create(&workers[i], NULL, do_thread, &index[i]);
82
		}
83
		printf("Waiting for workers to join\n");
84
		for (i = 0; i < 10; i++) {
85
			pthread_join(workers[i], NULL);
86
			printf("Worker %d joined\n", i);
87
		}
88
		printf("All workers joined\n");
89
		round += 1;
90
		printf("-----------------------------------------------------\n");
91
	}
92
}
(1-1/4)