xref: /aosp_15_r20/art/test/2275-pthread-name/native_getname.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef _GNU_SOURCE
18 #define _GNU_SOURCE
19 #endif
20 
21 #include "jni.h"
22 
23 #include <errno.h>
24 #include <pthread.h>
25 #include <stdio.h>
26 #include <string.h>
27 
Java_Main_printPthreadName(JNIEnv * env,jclass klass)28 extern "C" JNIEXPORT void JNICALL Java_Main_printPthreadName(
29     [[maybe_unused]] JNIEnv* env, [[maybe_unused]] jclass klass) {
30   constexpr size_t kBufSize = 20;  // Thread names are at most 16 characters.
31   char name[kBufSize];
32   int ret = pthread_getname_np(pthread_self(), name, kBufSize);
33   if (ret == 0) {
34     printf("%s\n", name);
35   } else {
36     fprintf(stderr, "pthread_getname_np failed: %s\n", strerror(ret));
37   }
38 }
39