5

I'm writing a program that needs to know what logical processor it's running on.

This question tells me how to do it in assembly, while this question tells me how to use this code in assembly without translating it to AT&T syntax.

Is there an easier way to do this using existing Linux system calls or library functions, or is it necessary for me to reinvent the wheel?

Community
  • 1
  • 1
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319
  • 2
    You could get that info but I'm not sure how long that info would be good as you could easily have that process rescheduled and run on another core at any time. – Jesus Ramos Feb 20 '12 at 09:25
  • The question you refer to doesn't do what you want. It tells you how many CPUs there are, not which CPU you're running on. – ugoren Feb 20 '12 at 09:54
  • @ugoren: you're right... I misread it – Nathan Fellman Feb 21 '12 at 21:29
  • follow this link: https://stackoverflow.com/questions/6491566/getting-the-machine-serial-number-and-cpu-id-using-c-c-in-linux – Hossein Oct 23 '17 at 22:32
  • @HosseinBobarshad: That's a different thing entirely. My question is about the logical processor ID of the logical processor that the thread is running on, while the question you pointed me to is about the model of the processor, and perhaps its serial number. – Nathan Fellman Oct 24 '17 at 10:37

3 Answers3

9

There's the linux specific getcpu call.

abyx
  • 69,862
  • 18
  • 95
  • 117
7

Tou can see sched_getcpu(). This glibc C function calls the getcpu Linux system call.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
onesuper
  • 196
  • 2
  • 7
  • Minimal runnable example demonstrating interaction with `sched_setaffinity`: https://stackoverflow.com/questions/280909/how-to-set-cpu-affinity-for-a-process-from-c-or-c-in-linux/54478296#54478296 – Ciro Santilli OurBigBook.com Oct 24 '19 at 13:15
-2

Try this , i am not sure that what you want is this

#include<stdio.h>
#include<sys/utsname.h>

int main()
{

char hostname[1024];
struct utsname userinfo;
if(uname(&userinfo)>=0)
{
  printf("\n***** System Details ******\n");
  printf("System Name    : %s\n",userinfo.sysname);
  printf("System Node    : %s\n",userinfo.nodename);
  printf("System Release : %s\n",userinfo.release);
  printf("System Version : %s\n",userinfo.version);
  printf("System Machine : %s\n",userinfo.machine);
}
else
 printf("\nSystem details fetch failed..\n");



if(gethostname(&hostname,1024)==0)
{
  printf("Hostname : %s\n",hostname);
}
else
 printf("\nHostname details fetch failed..\n");

return 0;
}
Akhil Thayyil
  • 9,263
  • 6
  • 34
  • 48