Home > Back-end >  Is it possible to pass popen() a string and have it return null?
Is it possible to pass popen() a string and have it return null?

Time:04-09

While working on line/branch coverage for a unit test, I came across the following code

bool run_command(char *command)
{
    FILE *handle = popen(command, "r");
    if (handle == nullptr)
    {
        std::cerr << "" << std::endl;
        return false;
    }

I've tried many different commands such as

"cat /dev/null | head"

but nothing seems to cause popen to fail. I also wrote a Python script, test.py,

for i in range(10000):
    print(i)

and passed "python test.py | head" to popen(). This causes a "broken pipe" error, but popen still returns a valid address.

Is it possible to pass a command string to popen function that will cause it to return null?

CodePudding user response:

I don't think so. glibc's popen ultimately calls posix_spawn, whose documentation says that it only fails if fork() fails. And that would have nothing to do with the filename.

Likewise, there are a few other ways that popen can fail before calling posix_spawn, but they aren't related to the filename; only conditions like running out of memory or file descriptors.

  • Related