LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to get stderr output when using a ::system() call (https://www.linuxquestions.org/questions/programming-9/how-to-get-stderr-output-when-using-a-system-call-616156/)

tmc3011 01-24-2008 09:31 PM

How to get stderr output when using a ::system() call
 
Hi,

I am trying to write a C++ application that wraps around the linux mount command.
I need to call
::system("mount /dev/sdc1 /mnt/test");
unfortunately this just returns 0 for success and nothing usefull on failure, all of the error messages are sent to stderr and I can't figure out how to redirect them.

none of the following worked
::system("mount /dev/sdc1 /mnt/test >& out.txt");
::system("mount /dev/sdc1 /mnt/test 2>&1 out.txt");
::system("mount /dev/sdc1 /mnt/test 2>&1 > out.txt");
::system("mount /dev/sdc1 /mnt/test | 2>&1 tee -a out.txt");
or
freopen("myfile.txt","w",stderr);
::system("mount /dev/sdc1 /mnt/test");
fclose();

Any suggestions?

I also did try using the mount(2) function, but after spending some time looking at the mount and nfsmount implementation in util-linux I realized that it was not going to be trivial and decided to use the mount(8) command. If anyone knows a way to implement using the nfs_mount_data funtion that would help also.

Thanks
Tamara

nadroj 01-24-2008 09:58 PM

i know you can change file descriptors to point to others, which i think would be what your looking for. hopefully youve done some pipe programming and other UNIX system programming, if so you should be able to figure it out without too much effort.

check man dup2. what this system call does is change one file descriptor (for example stderr) to point to another one. so what you can do is create your own file descriptor (or pipe i think) and set the output of stderr to go to your new fd (or pipe, i forget sorry!). once you have access to the file descriptor integer value, you can read it just like a normal file.

hope thats what your looking for

bigearsbilly 01-25-2008 04:17 AM

Code:

system("mount /dev/sdc1 /mnt/test > out.txt 2>&1");
order is important...

command 2>&1 1> outfile

means:send 2 to 1 (tty) then send 1 to outfile (2 still points at tty)

command 1> outfile 2>&1

means: send 1 to outfile then send 2 to 1 (outfile)


geddit?
;)


All times are GMT -5. The time now is 10:22 AM.