正确使用prctl()的方法

时间:2016-04-11 14:20:29

标签: c linux system-calls glibc variadic

prctl的原型是

int prctl(int option, unsigned long arg2, unsigned long arg3,
          unsigned long arg4, unsigned long arg5);
man page

,而在header中,它被声明为可变函数:

extern int prctl (int __option, ...) __THROW;
  1. 当我只需要2个时,我是否需要用5个参数调用它?
  2. 我是否需要将参数投射到unsigned long

1 个答案:

答案 0 :(得分:3)

只需传递你必须传递的内容,然后在其余参数中将{0}转换为unsigned long或完全跳过它们。当prctl被声明为可变函数时,它将相应地处理这种情况。

const char* name = "The user";
if (prctl(PR_SET_NAME, (unsigned long) name,
         (unsigned long)0, (unsigned long)0, (unsigned long)0) == -1)
{
    // handle error
    perror("prctl failed");
    return -1;
}

const char* name = "The user";
if (prctl(PR_SET_NAME, (unsigned long) name) == -1)
{
    // handle error
    perror("prctl failed");
    return -1;
}