Is it possible to prevent children inheriting the CPU/core affinity of the parent?

北慕城南 提交于 2020-01-14 20:01:54

问题


I'm particularly interesting in doing this on Linux, regarding Java programs. There are already a few questions that say you have no control from Java, and some RFEs closed by Sun/Oracle.

If you have access to source code and use a low-level language, you can certainly make the relevant system calls. However, sand-boxed systems - possibly without source code - present more of a challenge. I would have thought that a tool to set this per-process or an kernel parameter are able to control this from outside the parent process. This is really what I'm after.

I understand the reason why this is the default. It looks like some version of Windows may allow some control of this, but most do not. I was expecting Linux to allow control of it, but seems like it's not an option.


回答1:


Provided you have sufficient privileges, you could simply call setaffinity before execing in the child. In other words, from

if (fork() == 0)
        execve("prog", "prog", ...);

move to use

/* simple example using taskset rather than setaffinity directly */
if (fork() == 0)
        execve("taskset", "taskset", "-c", "0-999999", ...);

[Of course using 999999 is not nice, but that can be substituted by a program which automatically determined the number of cpus and resets the affinity mask as desired.]




回答2:


What you could also do, is change the affinity of the child from the parent, after the fork(). By the way, I'm assuming you're on linux, some of this stuff, such as retrieving the number of cores with sysconf() will be different on different OS's and unix flavors.... The example here, gets the cpu of the parent process and tries to ensure all child processes are scheduled on a different core, in round robin.

/* get the number of cpu's */
numcpu = sysconf( _SC_NPROCESSORS_ONLN );

/* get our CPU */
CPU_ZERO(&mycpuset);
sched_getaffinity( getpid() , sizeof mycpuset , &mycpuset);

for(i=0 ; i < numcpu ; i++ )
{
    if(CPU_ISSET( i, &mycpuset))
    {
        mycpu = i;
        break;
    }
}

//...

while(1)
{
    //Some other stuff.....

    /* now the fork */    
    if((pid = fork()) == 0)
    {
       //do your child stuff
    }    

   /* Parent... can schedule child. */
   else
   {
   cpu = ++cpu % numcpu;
       if(cpu == mycpu)
           cpu = ++cpu % numcpu;
       CPU_ZERO(&mycpuset);
       CPU_SET(cpu,&mycpuset);
       /*set processor affinity*/
       sched_setaffinity(pid, sizeof mycpuset, &mycpuset );

       //any other father stuff
   }
}


来源:https://stackoverflow.com/questions/4592575/is-it-possible-to-prevent-children-inheriting-the-cpu-core-affinity-of-the-paren

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!