xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/gettid/gettid02.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2023 SUSE LLC Andrea Cervesato <[email protected]>
4  */
5 /*\
6  * [Description]
7  *
8  * This test spawns multiple threads, then check for each one of them if the
9  * parent ID is different AND if the thread ID is different from all the other
10  * spwaned threads.
11  */
12 
13 #include "tst_test.h"
14 #include "lapi/syscalls.h"
15 #include "tst_safe_pthread.h"
16 
17 #define THREADS_NUM 10
18 
19 static volatile pid_t tids[THREADS_NUM];
20 
threaded(void * arg)21 static void *threaded(void *arg)
22 {
23 	int i = *(int *)arg;
24 	pid_t pid, tid;
25 
26 	pid = tst_syscall(__NR_getpid);
27 	tid = tst_syscall(__NR_gettid);
28 
29 	TST_EXP_EXPR(pid != tid,
30 		"parent ID (%d) differs from thread[%d] ID (%d)",
31 		pid, i, tid);
32 	tids[i] = tid;
33 	return NULL;
34 }
35 
run(void)36 static void run(void)
37 {
38 	pthread_t thread[THREADS_NUM];
39 	int args[THREADS_NUM];
40 	int error = 0;
41 
42 	for (int i = 0; i < THREADS_NUM; i++) {
43 		args[i] = i;
44 		SAFE_PTHREAD_CREATE(&thread[i], NULL, threaded, &args[i]);
45 	}
46 	for (int i = 0; i < THREADS_NUM; i++)
47 		SAFE_PTHREAD_JOIN(thread[i], NULL);
48 
49 	for (int i = 0; i < THREADS_NUM; i++) {
50 		for (int j = i + 1; j < THREADS_NUM; j++) {
51 			if (tids[i] == tids[j]) {
52 				tst_res(TINFO, "thread[%d] and thread[%d] have the same ID %d", i, j, tids[i]);
53 				error = 1;
54 			}
55 		}
56 	}
57 
58 	if (error)
59 		tst_res(TFAIL, "Some threads have the same TID");
60 	else
61 		tst_res(TPASS, "All threads have a different TID");
62 }
63 
64 static struct tst_test test = {
65 	.test_all = run,
66 };
67