1

I have a command that compiles test.cpp and is supposed to store output in the output file. Here is an example of my generated cmd:

g++ tmp/test.cpp -o tmp/test &> tmp/compile.out

when I use system(), it does not work. Even though it creates output file, it still prints everything to the main console window. When I execute it in terminal, it works just fine.

I also tried use popen() and fgets() (just copying the code from here) but same happened. I probably could just fork my process and use freopen or something but I have sockets and multiple threads running in the background. I guess they would be duplicated as well, which is not good.

Any ideas why it may fail?

2
  • Which platform are you on? According to the system manpage on my local Linux install, it specifically uses /bin/sh to execute the string. Redirect syntax differs between shells, and &> may be a bash extension. Whether /bin/sh is a symlink to bash may depend on platform/distribution. Commented Jan 31, 2012 at 12:05
  • I am using Ubuntu 11.10. Commented Jan 31, 2012 at 12:10

2 Answers 2

3

According to the man-page of system, it invokes sh which is the standard bourne shell (not bash, Bourne Again SHell). And the bourne shell doesn't understand &>. So you might need to use the old style:

g++ tmp/test.cpp -o tmp/test >tmp/compile.out 2>&1
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. Thank You. Will mark as an answer in 5 mins.
0

I tried the following variant on popen() and it worked for me under Mac OS X 10.7.2, gcc 4.2.1:

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

int main (int argc, char **argv)
{
    FILE *fpipe;
    char *cmd = "foo &> bar";

    if ( !(fpipe = (FILE*)popen(cmd,"r")) ) {
        perror("Problems with pipe");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

Compiling:

gcc -Wall test.c -o test

The binary test creates a file called bar, which contains the following output:

sh: foo: command not found

Which is what I would see if I typed foo &> bar at the shell.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.