我想创建一个自定义的打印函数,用法与 printf 相同,但为 pid 和 tid 添加 2 个参数。
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#include <sys/syscall.h>
int gettid() {
return syscall(__NR_gettid);
}
void print( const char *fmt,...) {
va_list vlist;
va_start(vlist, fmt);
va_end(vlist);
return;
}
int main() {
printf("%d %d hello\n",getpid(), gettid());
//print("hello\n");
return 0;
Run Code Online (Sandbox Code Playgroud)
实现打印功能的正确方法是什么?
让您的函数首先打印 pid 和 tid,然后用于vprintf打印剩下的内容。
void print( const char *fmt,...) {
va_list vlist;
printf("%d %d ", getpid(), gettid());
va_start(vlist, fmt);
vprintf(fmt, vlist);
va_end(vlist);
return;
}
Run Code Online (Sandbox Code Playgroud)