Is it possible to prevent the inheritance of child objects that inherit the parent / CPU affinity of the parent?

I am particularly interested in doing this on Linux, regarding Java programs. There are already several questions that say that you have no control over Java, and some RFEs are closed by Sun / Oracle.

If you have access to the source code and use a low level language, you can make the appropriate system calls. However, sandboxed systems - perhaps without source code - are a big problem. I would think that a tool to set this parameter for each process or kernel can control this from outside the parent process. This is really what I need.

I understand the reason this is the default value . It seems that some version of Windows may allow some control over this, but most of them do not. I expected Linux to allow it to be controlled, but it seems like this is not an option .

+3
source share
2 answers

If you have sufficient privileges, you can simply call setaffinity before executing in the child. In other words, from

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

go 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 good, but it can be replaced by a program that automatically determines the number of processors and resets the affinity mask as desired.]

+1
source

, , - fork(). , , Linux, , sysconf(), unix-... , , , .

/* get the number of cpu */
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
   }
}
+1

Source: https://habr.com/ru/post/1783380/


All Articles