简体   繁体   中英

Closing STDIN for a Qt Application

I am working on a project that has multiple C++ executables that communicate using named pipes. The main application (App1) spawns the rest of the applications. When spawning, it closes STDIN for the children using:

close(STDIN_FILENO);

And it redirects STDOUT and STDERR to other files that are specific to the child processes. This makes it so that the output from App1 is only from App1 and none of the children. It also allows App1 to accept input from STDIN and not let it get captured by the child processes.

One of the child processes is a Qt application. When spawned, it is using as much CPU as it can, slowing my computer considerably. If I do not close STDIN for the child processes, this behavior stops (but the children capture STDIN instead of the main process, which I don't want).

Why does this happen and how can I prevent the Qt applications from using all the CPU cycles?

Maybe give the Qt app what it wants? Use dup2 after fork but before exec ? dup2 will replace a given file descriptor with another so you can replace stdin with a file. Quick example:

if(fork() == 0)
{
   int somefd = open("somefile", O_RDONLY);
   // replace stdin (0) with somefd before exec-ing
   if(dup2(somefd, 0) == -1)
   {
      // cunning plan failed
   }
   // exec Qt app here
}

I think I figured out what the issue was while fixing another issue I was having. I was closing the STDIN file descriptor before redirecting the STDERR and STDOUT file descriptors. This was messing up the indexes that are used when I used freopen() to redirect them.

I moved the close() of STDIN to after the redirection, and don't seem to have the problem anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM